python-3.x - 如何对数据帧的特定元素执行算术运算?
问题描述
我试图了解如何在 python 中对数据帧执行算术运算。
import pandas as pd
import numpy as np
df = pd.DataFrame({'col1':[2,38,7,5],'col2':[1,3,2,4]})
print (unsorted_df.sum())
这就是我得到的(就输出而言),但我想更好地控制我得到的总和。
col1 52
col2 10
dtype: int64
只是想知道如何将数据框中的各个元素添加在一起。
解决方案
您的问题不是很清楚,但我仍然会尝试涵盖所有可能的情况,
输入:
df
col1 col2
0 2 1
1 38 3
2 7 2
3 5 4
如果你想要列的总和,
df.sum(axis = 0)
输出:
col1 52
col2 10
dtype: int64
如果你想要行的总和,
df.sum(axis = 1)
0 3
1 41
2 9
3 9
dtype: int64
如果要将数字列表添加到列中,
num = [1, 2, 3, 4]
df['col1'] = df['col1'] + num
df
输出:
col1 col2
0 3 1
1 40 3
2 10 2
3 9 4
如果要将数字列表添加到行中,
num = [1, 2]
df.loc[0] = df.loc[0] + num
df
输出:
col1 col2
0 3 3
1 38 3
2 7 2
3 5 4
如果要将单个数字添加到列中,则 df['col1'] = df['col1'] + 2 df
输出:
col1 col2
0 4 1
1 40 3
2 9 2
3 7 4
如果要将单个数字添加到行中,
df.loc[0] = df.loc[0] + 2
df
输出:
col1 col2
0 4 3
1 38 3
2 7 2
3 5 4
如果您想将一个数字添加到任何数字(第 i 行和第 j 列的元素),
df.iloc[1,1] = df.iloc[1,1] + 5
df
输出:
col1 col2
0 2 1
1 38 8
2 7 2
3 5 4
推荐阅读
- android - 如何删除 ConstraintLayout 中的空白空间
- javascript - 如何在保持纵横比的文章中创建简单的 3x3 网格?
- python - Django Mysql:MigrationSchemaMissing 错误窗口
- jquery - 将 div 与下一个 div 交换
- python-3.x - 在 pandas 中设置 csv 文件的子集
- javascript - 如何指定要在角度中包含代码覆盖文件的文件夹?
- sql - 有没有办法改变这个 BigQuery 自联接以使用窗口函数?
- c# - C# 中异步方法的匿名对象任务的正确返回类型
- c# - 从 C# 调用正在运行的访问应用程序的 msaccess 方法
- docker - 如何使用当前主机用户运行 Windows docker 容器?- 泊坞窗