2016-11-10 3 views
2

DataFrameの値を辞書を使って別のフレームの値に置き換えて動作させているコードがいくつか書かれていますが、辞書は非常に長くなることがあります。数千ペア。私はこのコードを使用すると非常に遅く実行されますが、それはまた数回の作業でメモリ不足になりました。大規模な辞書からDataFrameの値を置き換える方が良い

私のやり方は最適ではなく、これを行うにはもっと速い方法が必要であると私は幾分確信しています。私が望むことをする簡単な例を作成しましたが、それは大量のデータでは遅いです。誰かがこれを行う簡単な方法を持っていることを願っています。

import pandas as pd 

#Frame with data where I want to replace the 'id' with the name from df2 
df1 = pd.DataFrame({'id' : [1, 2, 3, 4, 5, 3, 5, 9], 'values' : [12, 32, 42, 51, 23, 14, 111, 134]}) 

#Frame containing names linked to ids 
df2 = pd.DataFrame({'id' : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'name' : ['id1', 'id2', 'id3', 'id4', 'id5', 'id6', 'id7', 'id8', 'id9', 'id10']}) 

#My current "slow" way of doing this. 

#Starts by creating a dictionary from df2 
#Need to create dictionaries from the domain and banners tables to link ids 
df2_dict = dict(zip(df2['id'], df2['name'])) 

#and then uses the dict to replace the ids with name in df1 
df1.replace({'id' : df2_dict}, inplace=True) 

答えて

1

私はあなたがSeriesmapを使用することができると思うがto_dictを変換 - df2の値を存在しない場合はNaNを得る:

df1['id'] = df1.id.map(df2.set_index('id')['name'].to_dict()) 
print (df1) 
    id values 
0 id1  12 
1 id2  32 
2 id3  42 
3 id4  51 
4 id5  23 
5 id3  14 
6 id5  111 
7 id9  134 

またはreplace、いけないdf1からdf2せ元の値に値を存在する場合:

df1['id'] = df1.id.replace(df2.set_index('id')['name']) 
print (df1) 
    id values 
0 id1  12 
1 id2  32 
2 id3  42 
3 id4  51 
4 id5  23 
5 id3  14 
6 id5  111 
7 id9  134 

サンプル:

#Frame with data where I want to replace the 'id' with the name from df2 
df1 = pd.DataFrame({'id' : [1, 2, 3, 4, 5, 3, 5, 9], 'values' : [12, 32, 42, 51, 23, 14, 111, 134]}) 
print (df1) 
#Frame containing names linked to ids 
df2 = pd.DataFrame({'id' : [1, 2, 3, 4, 6, 7, 8, 9, 10], 'name' : ['id1', 'id2', 'id3', 'id4', 'id6', 'id7', 'id8', 'id9', 'id10']}) 
print (df2) 

df1['new_map'] = df1.id.map(df2.set_index('id')['name'].to_dict()) 
df1['new_replace'] = df1.id.replace(df2.set_index('id')['name']) 
print (df1) 
    id values new_map new_replace 
0 1  12  id1   id1 
1 2  32  id2   id2 
2 3  42  id3   id3 
3 4  51  id4   id4 
4 5  23  NaN   5 
5 3  14  id3   id3 
6 5  111  NaN   5 
7 9  134  id9   id9 
+0

これは機能しているようです。しかし、df1の 'values'列を保持する方法はありますか? id列を変更して値の列を保持するためにこれを書く方法を理解することはできないようです。 Nvm、ちょうどそれを考え出した。 df1 ['id']。replace(df2.set_index( 'id')['name']、inplace = True) – Siesta

+0

申し訳ありませんが、私はasignを追加しません。 – jezrael

関連する問題