首页 > 解决方案 > 如何对数据帧的特定元素执行算术运算?

问题描述

我试图了解如何在 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

只是想知道如何将数据框中的各个元素添加在一起。

标签: python-3.xpandas

解决方案


您的问题不是很清楚,但我仍然会尝试涵盖所有可能的情况,

输入:

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

推荐阅读