我正在尝试解决这个常见问题,这是在尝试分解多个列并且相应列内的列表长度不同时引起的:
import pandas as pd
df = pd.DataFrame({'Student':['J.M.', 'M.G.', 'L.D.'], 'Subject':[['mathematics', 'history', 'literature'], ['physics', 'mathematics', 'geography', 'history'], ['latin', 'literature', 'mathematics']], 'Score':[[10, 8, 8.5], [5, 4, 8, 8.5], [4,5, 5]],'Score2':[[10], [5, 4, 8,8.5], [4,5, 5]]})
df = df.apply(pd.Series.explode)
在此示例中,第一个 Score
列表有 3 个元素,第一个 Score2
列表只有 1 个元素。我试图解决这个问题,应用一个函数来检查 to 列表的长度并向较短的列表附加一个空字符串。有更好的办法吗?
最佳答案
IIUC,您可以运行爆炸的 for 循环:
for col in df:
df = df.explode(col)
我明白了
>>> df
Student Subject Score Score2
0 J.M. mathematics 10 10
0 J.M. mathematics 8 10
0 J.M. mathematics 8.5 10
0 J.M. history 10 10
0 J.M. history 8 10
.. ... ... ... ...
2 L.D. mathematics 5 5
2 L.D. mathematics 5 5
2 L.D. mathematics 5 4
2 L.D. mathematics 5 5
2 L.D. mathematics 5 5
[100 rows x 4 columns]
关于python - 解决值错误: cannot reindex from a duplicate axis when exploding multiple columns with different lenghts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67403688/