我有一个这样的示例数据框,列:ID
和 Main
ID,Main
0,[30 115 266 38;662 99 1199 43] [511 133 25 47] [664 162 49 22]
如何使用 pandas 使我的数据框如下所示
预期输出
ID,Main
0,30 115 266 38
0,662 99 1199 43
0,511 133 25 47
0,664 162 49 22
最佳答案
第一个replace
;
by ][
然后提取 []
之间的值 findall
对于列表
的系列
。
最后创建DataFrame
,通过stack
reshape 通过 reset_index
进行一些数据清理:
s = df['Main'].fillna('').str.replace(';','][').str.findall('\[(.*?)\]')
df = (pd.DataFrame(s.values.tolist(), index=s.index)
.stack()
.reset_index(level=1, drop=True)
.reset_index())
df.columns = ['ID','Main']
print (df)
ID Main
0 0 30 115 266 38
1 0 662 99 1199 43
2 0 511 133 25 47
3 0 664 162 49 22
Series
的另一种解决方案:
s = df['Main'].fillna('').str.strip('[]').str.split(';|\]\s+\[')
关于python - 使用相同的 Id,pandas 从多个列表创建多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51894603/