pandas 在字符串列中求和用逗号分隔的整数 [英] Pandas sum integers separated by commas in a string column
本文介绍了 pandas 在字符串列中求和用逗号分隔的整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个pandas数据框,其中一列为字符串类型,如下所示:
I have a pandas data frame with a column as type string, looking like:
1 1
2 3,1
3 1
4 1
5 2,1,2
6 1
7 1
8 1
9 1
10 4,3,1
我想对所有用逗号分隔的整数求和,结果是:
I want to sum all integers separated by the commas, obtaining as a result:
1 1
2 4
3 1
4 1
5 5
6 1
7 1
8 1
9 1
10 8
到目前为止,我的尝试是:
My attempt so far has been:
qty = []
for i in df['Qty']:
i = i.split(",")
i = sum(i)
qty.append(i)
df['Qty'] = qty
尽管出现错误:
TypeError: cannot perform reduce with flexible type
推荐答案
在列上使用apply
进行df['B'].apply(lambda x: sum(map(int, x.split(','))))
In [81]: df
Out[81]:
A B
0 1 1
1 2 3,1
2 3 1
3 4 1
4 5 2,1,2
5 6 1
6 7 1
7 8 1
8 9 1
9 10 4,3,1
In [82]: df['B'].apply(lambda x: sum(map(int, x.split(','))))
Out[82]:
0 1
1 4
2 1
3 1
4 5
5 1
6 1
7 1
8 1
9 8
Name: B, dtype: int64
这篇关于 pandas 在字符串列中求和用逗号分隔的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文