我有一个200行的excel文件,其中2行有逗号分隔值.如果我将它们输出到制表符分隔符,它将如下所示:
col1 col2 col3
a b,c d,e
f g,h i,j
Run Code Online (Sandbox Code Playgroud)
我需要爆炸才能获得这样的数据帧,将200行扩展到~4,000:
col1 col2 col3
a b d
a b e
a c d
a c e
f g i
f g j
f h i
f h j
Run Code Online (Sandbox Code Playgroud)
我没有在pandas中看到任何爆炸功能,并且无法弄清楚如何使逗号分隔值的列长度不均匀 - 不确定分割在这里如何工作.
帮助我堆叠溢出,你是我唯一的希望.谢谢!
使用itertools.product获取col2和col3之间的所有组合,然后将它们转换为单独的列
from itertools import product
df.set_index('col1')\
.apply(lambda x: pd.Series(list(product(x.col2.split(','),x.col3.split(',')))),axis=1)\
.stack()\
.reset_index(1,drop=True)\
.apply(pd.Series)\
.reset_index().rename(columns={0:'col1',1:'col3'})
Out[466]:
col1 col1 col3
0 a b d
1 a b e
2 a c d
3 a c e
4 f g i
5 f g j
6 f h i
7 f h j
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
95 次 |
| 最近记录: |