我有两个爸爸
df1
col_1 col_2 col_3
1 a1 "text1"
2 a2 "text2"
3 a1 "text3"
4 a1 "text4"
df2
col_1 col_2
1 a1
2 a2
3 a3
df1的col_2中出现了多个值(学生),而df2只出现了一个。我对df1的col_3中的文本感兴趣。
我需要将df1的文本列插入到df2中,处理col_2的多次出现。
final_df
col_1 col_2 text_from_df1
1 a1 ["text1,"text3","text4"]
2 a2 ["text2"]
3 a3 NaN
有什么好办法吗?我在这里有点疑惑。
您可以使用 groupby
关于 df1
然后 right
merge
根据它们的具体栏目 col_2
:
df_final = pd.merge(df1.groupby('col_2')['col_3'].apply(list), df2, left_on=['col_2'], right_on = ['col_2'], how = 'right')
产出。
col_2 col_3 col_1
0 a1 [text1, text3, text4] 1
1 a2 [text2] 2
2 a3 NaN 3
>>> df2.merge(df1.groupby('col_2')['col_3'].apply(list).rename('text_from_df1').reset_index(), how='left')
col_1 col_2 text_from_df1
0 1 a1 ["text1", "text3", "text4"]
1 2 a2 ["text2"]
2 3 a3 NaN
你最好不要保留一个 "小号"。list
类型的对象,因为它可能导致复杂的道路。