python - 加入合并多个数据框
问题描述
我的数据是这样的:
Name test1 test2 test3 Count
Emp1 X,Y A a1,a2 1
Emp2 X A,B,C a3 2
Emp3 Z C a4,a5,a6 3
将具有多个值的test1和test2单元格拆分为单独的行并将它们合并在一起。
df2 = df.test1.str.split(',').apply(pd.Series)
df2.index = df.set_index(['Name', 'Count']).index
df2=df2.stack().reset_index(['Name', 'Count'])
df3 = df.test2.str.split(',').apply(pd.Series)
df3.index = df.set_index(['Name', 'Count']).index
df3=df3.stack().reset_index(['Name', 'Count'])
df2.merge(df3,on=['Name', 'Count'],how='outer')
出的代码是:
Out[132]:
Name Count 0_x 0_y
0 Emp1 1 X A
1 Emp1 1 Y A
2 Emp2 2 X A
3 Emp2 2 X B
4 Emp2 2 X C
5 Emp3 3 Z C
将具有多个值的 Test3 拆分为单个行的代码
df4.index = df.set_index(['Name', 'Count']).index
df4=df4.stack().reset_index(['Name', 'Count'])
谁能帮助我,如何将Test3 与 test2 和 test1多连接,就像我在上面的代码中合并了 Test1 和 Test 一样?
解决方案
(不确定我理解正确,但是)以下this answer
,你可以
expand(expand(df.drop('test3', 1), 'test1', ','), 'test2')
或者
expand_all(df.drop('test3', axis=1), cols=['test1', 'test2'], seps=[',', ','])
两者都输出
Name test1 test2 Count
0 Emp1 X A 1
1 Emp1 Y A 1
2 Emp2 X A 2
3 Emp2 X B 2
4 Emp2 X C 2
5 Emp3 Z C 3
细节:
def expand(df, col, sep=','):
r = df[col].str.split(sep)
d = {c: df[c].values.repeat(r.str.len(), axis=0) for c in df.columns}
d[col] = [i for sub in r for i in sub]
return pd.DataFrame(d)
推荐阅读
- java - Apache Camel:如何迭代列表并调用rest api?
- python - 在具有多个 python 版本的 Ubuntu 18.04 中卸载所有 Python 包
- python - Python BigQuery:插入内容为数字的字符串失败
- c - C 如何正确存储 sqlite3 行数据?
- ubuntu-16.04 - Ejabberd 19 在安装时抛出“deps/.got”异常
- javascript - 如何提交从php生成的多个表单
- automated-tests - 如何在 Visual Studio 2019 中单独运行选定的测试
- yammer - 通过 Yammer 上的 API 发布富文本消息
- wordpress - plesk 子文件夹/blog wordpress nginx 404 未找到
- sql-server - 在同一台计算机上从 SQL Server Express 切换到 SQL Server Developer 版本