2つのデータフレームのデータを結合したいと思います。データフレームは文字列です
df1=pd.read_csv('test1.csv',encoding='utf8',index_col=['id_df1'],header=0)
df2=pd.read_csv('test2.csv',encoding='utf8',index_col=['id_df2'],header=0)
print(df1)
print(df2)
out:
id_df1 student contact_person
1 john Amy
2 jeff Cindy
3 steven Bob
4 tina Amy
id_df2 student parents_list
1 tina (Amy) (Bob)
2 steven (Eric) (Bob)
3 john (Amy)
4 jeff (Frank) (Harry)
print(type(df1['contact_person'][0]))
print(type(df2['parents_list'][0]))
out:
<class 'str'>
<class 'str'>
if df1 ['student'] == df2 ['student']&df1 ['contact_person'] match df2 ['parents_list']
次のような「outer」メソッドを使用します。
output
id_df1 id_df2 student contact_person parents
0 1 3 john Amy (Amy)
1 3 2 steven Bob (Eric) (Bob)
2 4 1 tina Amy (Amy) (Bob)
3 2 null jeff Cindy null
4 null 4 jeff null (Frank) (Harry)
1つの方法は次のとおりです。最初に、条件が満たされた場合にdf1
列を作成しますbool
。
df1['bool'] = df1.apply(lambda row: True if row['contact_person'] in df2['parents_list'][df2['student'] == row['student']].iloc[0] else False,1)
次にmerge
、条件が満たされている場合と満たさdf_yes
れappend
ていない場合がありdf_no
ます。
df_yes = df1[df1['bool'] == True].\
merge(df2, on='student', how = 'left').drop('bool',1)
df_no = df1[df1['bool'] == False].\
append(df2[df2['student'].isin(df1['student'][df1['bool'] == False])]).drop('bool',1)
最後にappend
両方だけ:
list_ordered_col = ['id_df1', 'id_df2', 'student', 'contact_person', 'parents_list']
df_output = df_yes.append(df_no)[list_ordered_col ].\
reset_index(drop=True)
注:parent_listの以前の入力で機能していました(a、b、c ...の場合)
編集:置換df1['bool']=...
:
def parantes_in_parentList (row, df_list):
df_parent_list = df_list['parents_list'][df_list['student'] == row['student']]
if not df_parent_list.empty:
if row['contact_person'] in df_parent_list.iloc[0]:
return True
# return False in all the other case
return False
df1['bool'] = df1.apply(parantes_in_parentList , args=([df2]),axis=1)
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加