python-3.x - 对 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
解决方案
我想我们可以分开
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
推荐阅读
- elasticsearch - 弹性搜索 REST 查询返回超出预期
- r - 带有两个变量的点图
- java - GraphQL 查询解析器作为单独的 Web 事务
- python - 首次尝试使用导入请求时 Python 连接被拒绝
- google-bigquery - 如何在不使用 case 语句的情况下在 BigQuery 中创建数据透视表
- plc - 为什么我不能将输出变量作为参数传递给 IEC61131-3 结构化文本 (TwinCAT3) 中的功能块构造函数?
- elasticsearch - 创建一个包含 N 个区间为 X 的桶的直方图,其中最后一个桶还包括大于其区间的计数
- python-3.x - 更改 Pandas 数据框中的列值以将数字显示为 Milions
- ajax - 断开互联网时,Ajax getElementById 停止工作
- ruby-on-rails - before_action :find_transaction 不起作用 rails api