Python Pandas-将多行从另一个DF映射到多个列
我有两个数据帧,我正在尝试将数据从一个Python Pandas-将多行从另一个DF映射到多个列,python,pandas,dataframe,Python,Pandas,Dataframe,我有两个数据帧,我正在尝试将数据从一个df1迁移到我的主df 它们共享一个公共键,我想将df1行中的值存储到df列中。这是我能做的但是df1可以有多行(最多5行)共享公共密钥,并且我希望将每行存储在单个列中。 举个例子: df df1 输出: index key datacol newcol1 newcol2 newcol3 1 1AA data1 new1 2 1AB data2 new2 new3 new4 3 1AC
df1
迁移到我的主df
它们共享一个公共键,我想将df1
行中的值存储到df
列中。这是我能做的但是df1
可以有多行(最多5行)共享公共密钥,并且我希望将每行存储在单个列中。
举个例子:
df
df1
输出:
index key datacol newcol1 newcol2 newcol3
1 1AA data1 new1
2 1AB data2 new2 new3 new4
3 1AC data3 new5 new6
感谢您的帮助。您可以先合并
newdf=df.merge(df1,how='right')
然后使用cumcount
创建帮助键,然后问题看起来像pivot
finaldf= newdf.assign(helpkey=newdf.groupby('key').cumcount()).set_index(['key','datacol','helpkey']).newdata.unstack(fill_value='')
finaldf
Out[410]:
helpkey 0 1 2
key datacol
1AA data1 new1
1AB data2 new2 new3 new4
1AC data3 new5 new6
IIUC,我能做什么
d = df2.groupby('key', as_index=False).agg(list)
x = pd.concat([d.newdata.apply(pd.Series), d.key],1).set_index('key')
pd.merge(df.set_index('key'),x, right_index=True, left_index=True)
index datacol 0 1 2
key
1AA 1 data1 new1 NaN NaN
1AB 2 data2 new2 new3 new4
1AC 3 data3 new5 new6 NaN
finaldf= newdf.assign(helpkey=newdf.groupby('key').cumcount()).set_index(['key','datacol','helpkey']).newdata.unstack(fill_value='')
finaldf
Out[410]:
helpkey 0 1 2
key datacol
1AA data1 new1
1AB data2 new2 new3 new4
1AC data3 new5 new6
d = df2.groupby('key', as_index=False).agg(list)
x = pd.concat([d.newdata.apply(pd.Series), d.key],1).set_index('key')
pd.merge(df.set_index('key'),x, right_index=True, left_index=True)
index datacol 0 1 2
key
1AA 1 data1 new1 NaN NaN
1AB 2 data2 new2 new3 new4
1AC 3 data3 new5 new6 NaN