【发布时间】:2017-01-12 19:51:23
【问题描述】:
假设我有两个数据框:
import pandas as pd
import numpy as np
df1 = pd.DataFrame({'person':[1,1,2,2,3], 'sub_id':[20,21,21,21,21], 'otherval':[np.nan, np.nan, np.nan, np.nan, np.nan], 'other_stuff':[1,1,1,1,1]}, columns=['person','sub_id','otherval','other_stuff'])
df2 = pd.DataFrame({'sub_id':[20,21,22,23,24,25], 'otherval':[8,9,10,11,12,13]})
我希望df1 中的person 的每个级别都具有sub_id 的所有级别(包括任何重复项)及其各自的otherval 来自df2。换句话说,我的合并结果应该是这样的:
person sub_id otherval other_stuff
1 20 8 1
1 21 9 NaN
1 22 10 NaN
1 23 11 Nan
1 24 12 NaN
1 25 13 NaN
2 20 8 NaN
2 21 9 1
2 21 9 1
2 22 10 NaN
2 23 11 NaN
2 24 12 NaN
2 25 13 NaN
3 20 8 NaN
3 21 9 1
3 22 10 NaN
3 23 11 NaN
3 24 12 NaN
3 25 13 NaN
注意person==2 有两 行,而sub_id==21。
【问题讨论】:
-
请修正
df1的定义,所有列的长度必须相同。 -
@Abdou 刚刚修好了,谢谢。
-
试试
df1.groupby('person').apply(lambda x: pd.merge(x,df2, on='sub_id', how='right')).reset_index(level = (0,1), drop = True).ffill()。 -
@Abdou 我相信这行得通!除了我不想向前填充我的所有列;只是
person列。 -
df1.groupby('person').apply(lambda x: pd.merge(x,df2, on='sub_id', how='right')).reset_index(level = (0,1), drop = True)得到你想要的输出,但你必须用.ffill()方法填充person。
标签: python pandas join dataframe merge