【问题标题】:Calculate the sum of the numbers separated by a comma in a dataframe column计算数据框列中用逗号分隔的数字的总和
【发布时间】:2019-12-20 13:44:55
【问题描述】:

我正在尝试计算数据框列中用逗号分隔的所有数字的总和,但是我不断出错。这就是数据框的样子

Description  scores
logo    
graphics    
eyewear      0.360740,-0.000758
glasses      0.360740,-0.000758
picture      -0.000646
tutorial     0.001007,0.000968,0.000929,0.000889 
computer     0.852264  0.001007,0.000968,0.000929,0.000889

这就是代码的样子

test['Sum'] = test['scores'].apply(lambda x: sum(map(float, x.split(','))))

但是我不断收到以下错误

ValueError: could not convert string to float:

我认为这可能是因为数据框开头缺少值。但是我对数据框进行了子集化以排除缺少的值,但仍然出现相同的错误。

输出

Description  scores                                               SUM
logo    
graphics    
eyewear      0.360740,-0.000758                                0.359982
glasses      0.360740,-0.000758                                0.359982
picture      -0.000646                                        -0.000646
tutorial     0.001007,0.000968,0.000929,0.000889               0.003793
computer     0.852264  0.001007,0.000968,0.000929,0.000889     0.856057 

我知道我可能遗漏了非常小的东西,但是我无法弄清楚,有人可以帮我解决它。

提前致谢

【问题讨论】:

    标签: python-3.x pandas dataframe lambda apply


    【解决方案1】:

    有时使用 Python 似乎非常有效,这可能就是其中之一。

    df['scores'].apply(lambda x: sum(float(i) if len(x) > 0 else np.nan for i in x.split(',')))
    
    0         NaN
    1         NaN
    2    0.359982
    3    0.359982
    4   -0.000646
    5    0.003793
    6    0.856057
    

    【讨论】:

    • 非常感谢您的回复。
    【解决方案2】:

    你可以str.split

    df.scores.str.split(',',expand=True).astype(float).sum(1).mask(df.scores.isnull())
    0         NaN
    1         NaN
    2    0.359982
    3    0.359982
    4   -0.000646
    5    0.003793
    6    0.856057
    dtype: float64
    

    【讨论】:

    • 输出应该是前两行应该有空白/缺失值。我已经更新了问题中的输出数据框
    • 非常感谢您的更新,我相信这会在您的最后工作,不知道为什么它不适用于 y 数据框
    【解决方案3】:

    另一种使用explode、groupby和sum函数的解决方案:

    df.scores.str.split(',').explode().astype(float).groupby(level=0).sum(min_count=1)
    0         NaN
    1         NaN
    2    0.359982
    3    0.359982
    4   -0.000646
    5    0.003793
    6    0.856057
    Name: scores, dtype: float64
    

    或者让@WeNYoBen 的回答稍微短一些”:

    df.scores.str.split(',',expand=True).astype(float).sum(1, min_count=1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 2018-06-13
      • 2021-10-09
      相关资源
      最近更新 更多