【问题标题】:Convert list to int and sum all elements in pandas dataframe将列表转换为 int 并对 pandas 数据框中的所有元素求和
【发布时间】:2020-07-20 10:06:40
【问题描述】:

对 pandas 非常陌生,我正在尝试将一个列表的元素汇总到一个 pandas 数据框的单列中,但我找不到这样做的方法

数据框看起来像这样:

index codes 
0     [19, 19]
1     [3, 4]
2     [20, 5, 3]
3     NaN
4     [1]
5     NaN
6     [14, 2]

我想要得到的是:

index codes       total 
0     [19, 19]    38
1     [3, 4]      7 
2     [20, 5, 3]  28
3     NaN         0 
4     [1]         1
5     NaN         0
6     [14, 2]     16

但是代码中的值是通过使用来自不同列的str.findall('-(\d+)') 获得的,因此它们不是整数列表

任何帮助将不胜感激,谢谢。

【问题讨论】:

    标签: python pandas list dataframe


    【解决方案1】:

    如果您想要 int 类型输出,请尝试 df['total'] = df['codes'].apply(lambda x:int(np.nansum(x)))

    否则请尝试df['total'] = df['codes'].apply(lambda x:np.nansum(x))

    【讨论】:

      【解决方案2】:

      我会使用str.extractall() 而不是str.findall()

      # replace orig_column with the correct column name
      df['total'] = (df['orig_column'].str.extractall('-(\d+)')
                       .astype(int).sum(level=0)
                       .reindex(df.index, fill_value=0)
                    )
      

      如果您真的想使用当前的codes 列:

      df['total'] = df['codes'].explode().astype(float).sum(level=0)
      

      输出:

         index       codes  total
      0      0    [19, 19]     38
      1      1      [3, 4]      7
      2      2  [20, 5, 3]     28
      3      3         NaN      0
      4      4         [1]      1
      5      5         NaN      0
      6      6     [14, 2]     16
      

      【讨论】:

      • 谢谢!我花了一个多小时在 pandas 字符串列中寻找求和数字的答案,这是第一个真正起作用的答案
      【解决方案3】:
      df['total'] = (
          df.codes.apply(lambda x: sum([int(e) for e in x]) if type(x) == list else 0)
      )
      

      【讨论】:

        猜你喜欢
        • 2018-12-15
        • 1970-01-01
        • 2021-08-08
        • 2019-08-14
        • 1970-01-01
        • 1970-01-01
        • 2013-07-30
        • 2018-05-17
        相关资源
        最近更新 更多