pandas.DataFrame.explode生成太多行

2024-09-29 17:15:54 发布

您现在位置:Python中文网/ 问答频道 /正文

给出以下数据:

data = {'type': ['chisel', 'disc', 'user_defined'],
        'depth': [[152, 178, 203],  [127, 152, 178, 203], [0]],
        'residue': [[0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0], [0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0], [0.0]],
        'timing': [["10-nov", "10-apr"], ["10-nov", "10-apr"], ["10-apr"]]}

创建df

^{pr2}$

按预期输出:

enter image description here

explodetiming:

df = df.explode('timing')

按预期输出:

  • 为计时中的每个项目增加一行

enter image description here

explodedepth:

df = df.explode('depth')

输出不符合预期

  • 我希望chisel有6行,8行disc
    • 每个3个,用于10-apr&;10-nov,用于chisel
    • 每个4个,用于10-apr&;10-nov,用于disc
  • explode的产量是预期的两倍
    • 12而不是6,对于chisel
    • 16而不是8,对于disc

enter image description here

问题:

  • 我的期望不正确吗?在
  • 我是不是用错了explode?在

Tags: 数据dfdatatypenovaprampdisc
1条回答
网友
1楼 · 发布于 2024-09-29 17:15:54

无论何时使用重复索引,pandas都会产生意外的结果。请注意,在第一个explode之后,您将得到重复的索引。在

重置它们将产生一个如您所期望的那样工作的数据帧。在

df.explode('timing').reset_index(drop=True).explode('depth')

^{pr2}$

相关问题 更多 >

    热门问题