python - Pandas - 将多行从另一个 DF 映射到多列
问题描述
我有两个数据框,我正在尝试将数据从一个迁移df1
到我的 main df
。
它们共享一个公共键 - 我想将一行中的值存储df1
到一df
列中。我可以这样做..但是 df1
可以有多行(最多 5 行)共享公共键,我想将每一行存储在一个单独的列中。
使用示例:
df
index key datacol
1 1AA data1
2 1AB data2
3 1AC data3
df1
index key newdata
1 1AA new1
2 1AB new2
3 1AB new3
4 1AB new4
5 1AC new5
6 1AC new6
输出:
index key datacol newcol1 newcol2 newcol3
1 1AA data1 new1
2 1AB data2 new2 new3 new4
3 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
推荐阅读
- css - 当输入为只读时设置输入占位符的样式
- javascript - 带有联合的条件类型
- php - 用数组键中的通配符替换字符串值(例如:width=* => width=100)
- php - PHP:如何只允许注册用户进入另一个页面
- apache - sudo yum install httpd 抛出错误
- typescript - 打字稿多文件命名空间导出错误
- scrapy - 运行 vagrant up 时无法重命名目录以在 Virtualbox 中保存设置文件
- matlab - 如何从 MATLAB 中的矩阵创建子矩阵(全部 5*5)?
- html - 内容未正确填充 CSS 网格列
- c - 遍历数组似乎不起作用