【问题标题】:Call pandas explode on one column, and divide the other columns accordingly调用 pandas 在一列上爆炸,并相应地划分其他列
【发布时间】:2022-08-23 17:48:50
【问题描述】:

我有一个像下面这样的数据框

d = {\"to_explode\": [[1, 2, 3], [4, 5], [6, 7, 8, 9]], \"numbers\": [3, 2, 4]}
df = pd.DataFrame(data=d)

    to_explode      numbers
0   [1, 2, 3]       3
1   [4, 5]          4
2   [6, 7, 8, 9]    12

我想在类似列表的列上调用pd.explode,但我想相应地划分另一列中的数据。

在此示例中,第一行的 numbers 列中的值将替换为 1 - 即 3 / 3(to_explode 列中的相应项目数)。

请问我该怎么做?

    标签: python pandas explode


    【解决方案1】:

    您需要执行计算(使用str.len 获取列表长度),然后是explode

    out = (df
     .assign(numbers=df['numbers'].div(df['to_explode'].str.len()))
     .explode('to_explode')
    )
    

    输出:

      to_explode  numbers
    0          1      1.0
    0          2      1.0
    0          3      1.0
    1          4      1.0
    1          5      1.0
    2          6      1.0
    2          7      1.0
    2          8      1.0
    2          9      1.0
    

    【讨论】:

      猜你喜欢
      • 2020-04-10
      • 2022-11-03
      • 2016-08-02
      • 1970-01-01
      • 1970-01-01
      • 2019-04-07
      • 1970-01-01
      • 1970-01-01
      • 2022-11-11
      相关资源
      最近更新 更多