首页 > 解决方案 > 对 pandas 列中的所有元素求和

问题描述

我在 Python 数据框中的一列中有一个数据。

1-2 3-4 8-9
4-5 6-2
3-1 4-2 1-4

需要对该列中的所有可用数据求和。

我试图应用以下逻辑,但它不适用于列表列表。

lst=[]
str='5-7 6-1 6-3'
str2 = str.split(' ')
for ele in str2:
    lst.append(ele.split('-'))
print(lst)
sum(lst)

谁能告诉我最简单的方法?

我的预期结果应该是:

27
17
15

标签: python-3.xpandasdataframe

解决方案


我想我们可以分开

df.col.str.split(' |-').map(lambda x : sum(int(y) for y in x))
Out[149]: 
0    27
1    17
2    15
Name: col, dtype: int64

或者

pd.DataFrame(df.col.str.split(' |-').tolist()).astype(float).sum(1)
Out[156]: 
0    27.0
1    17.0
2    15.0
dtype: float64

推荐阅读