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

标签 python pandas

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

相关文章:

python - 在python中将表格写入CSV文件

python - PyCharm Python 输出对于大型数据集会崩溃

python - 如何计算 pandas datetime 对象的均值和方差?

python - 用填充的 0 来通配一个范围 - python

python - 如何过滤掉列中的重复值(每行)

python - 设置 QButton 高度

python - 根据pandas中的另一个列值有条件地填充列值

Python 如何在电子邮件正文中使用 DataFrame 输出作为文本

python - 使用 Python 根据条件替换数据框中的所有值(所有列)

python - PyCUDA:设备代码中的 Pow 尝试使用 std::pow,失败