python - 解决值错误: cannot reindex from a duplicate axis when exploding multiple columns with different lenghts

标签 python pandas dataframe

我正在尝试解决这个常见问题,这是在尝试分解多个列并且相应列内的列表长度不同时引起的:

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/

相关文章:

python - 使用pytest测试多个选项

python - 如何匹配正则表达式模式并使用 Pandas 将其替换为匹配组?

python - 在 Python 中将 git commit hash 通过管道传输到文件

Python for循环遍历一列的所有行

python - 将包含分组数据的 CSV 导入到 Pandas 数据框中

名称列表的 Python 文件操作

python - pandas:如何限制 str.contains 的结果?

python - Pandas 检查时间序列的连续性

r - 使用来自两个不同数据帧的字符向量作为 lm 函数回归的公式

python - Pandas :在公共(public)列上添加两个数据框