我有一个 pandas 数据框,其中有一列为字符串类型,如下所示:
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
我想对所有用逗号分隔的整数求和,得到结果:
1 1
2 4
3 1
4 1
5 5
6 1
7 1
8 1
9 1
10 8
到目前为止我的尝试是:
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
关于python - Pandas 对字符串列中以逗号分隔的整数求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32947781/