私は2つのパンダDataFrameを持っています:
df_topics_temp contains
列のある行列 id
df_mapping contains
マッピングid
AへparentID
私は、列移入しようとしているparent.id
中df_topics_temp
でparentID
中をdf_mapping
。
非常に面倒ですが、ループを使用してソリューションを作成しました。できます。パンダ.apply
を使用した私の解決策はdf_topics_temp
機能しません
解決策1(動作):
def isnan(value):
try:
import math
return math.isnan(float(value))
except:
return False
for x in range(0, df_topics_temp['id'].count()):
topic_id_loop = df_topics_temp['topic.id'].iloc[x]
mapping_row = df_mapping[df_mapping['id'] == topic_id_loop]
parent_id = mapping_row['parentId'].iloc[0]
if isnan(parent_id):
df_topics_temp['parent.id'].iloc[x] = mapping_row['id'].iloc[0]
else:
df_topics_temp['parent.id'].iloc[x] = topic_id_loop
解決策2(機能しません):
def map_function(x):
df_topics_temp = df_mapping.loc[df_mapping['id'] == x]
temp = df_topics_temp['parentId'].iloc[0]
return temp
df_topics_temp['parent.id'] = df_topics_temp['topic.id'].apply(map_function)
df_topics_temp.head()
2番目の解決策(パンダ.apply
)は、のparent.id
列にデータを入力していませんdf_topics_temp
。
お手伝いありがとう
<ipython-input-68-a2e8d9a21c26> in map_function(row)
1 def map_function(row):
----> 2 row['parent.id'] = df_mapping.loc[df_mapping['id']==row['topic.id']]['parentId'].values[0]
3 return row
IndexError: ('index 0 is out of bounds for axis 0 with size 0', 'occurred at index 190999')
私が正しく理解していれば、「apply」は行を取り、行を返します。したがって、関数で行を返す必要があります。あなたは値を返します。例えば:
#setting up the dataframes
import pandas as pd
import numpy as np
df1 = pd.DataFrame.from_dict({'name':['alice','bob'],'id':[1,2]})
mapping = pd.DataFrame.from_dict({'id':[1,2,3,4],'parent_id':[100,200,100,200]})
#mapping function
def f(row):
if any(mapping['id']==row['id']):
row['parent_id'] = mapping.loc[mapping['id']==row['id']]['parent_id'].values[0]
else: # missing value
row['parent_id'] = np.nan
return row
df1.apply(f,axis=1)
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加