忽然笑
简单循环
最简单的方式就是循环拆分一下呗。先上最简单方法:
import pandas as pd
df = pd.DataFrame({'A':['1','2','3'],'B':['1','2,3','4,5,6'],'C':['3','3','3']})
result = pd.DataFrame(columns=['A','B','C'])
print(df,'\n')
for i in df.itertuples():
for j in i[2].split(','):
result = result.append({'A':i[1],'B':j,'C':i[3]},ignore_index=True)
print(result)
输出:
A B C
0 1 1 3
1 2 2,3 3
2 3 4,5,6 3
A B C
0 1 1 3
1 2 2 3
2 2 3 3
3 3 4 3
4 3 5 3
5 3 6 3
更高效的方法
采用expand直接进行扩展
df = pd.DataFrame({'A':['1','2','3'],'B':['1','2,3','4,5,6'],'C':['3','3','3']})
df = (df.set_index(['A','C'])['B']
.str.split(',', expand=True)
.stack()
.reset_index(level=2, drop=True)
.reset_index(name='B'))
print(df)