gpt4 book ai didi

python - Pandas 对字符串列中以逗号分隔的整数求和

转载 作者:行者123 更新时间:2023-12-01 04:27:04 26 4
gpt4 key购买 nike

我有一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com