Python 数据帧中所有列的数学运算,无论其大小
从中我得到了一个简单的表格:Python 数据帧中所有列的数学运算,无论其大小,python,pandas,statistics,Python,Pandas,Statistics,从中我得到了一个简单的表格: import pandas as pd import numpy as np d = {'col1': [100, 198, 495, 600, 50], 'col2': [99, 200, 500, 594, 100], 'col3': [101, 202, 505, 606, 150]} df = pd.DataFrame(data=d) df 从这里,我想取第一行中所有值的%CV,然后是第二行,依此类推 我希望无论表有多少列,它都能工作 我可以用几行代码来实
import pandas as pd
import numpy as np
d = {'col1': [100, 198, 495, 600, 50], 'col2': [99, 200, 500, 594, 100], 'col3': [101, 202, 505, 606, 150]}
df = pd.DataFrame(data=d)
df
从这里,我想取第一行中所有值的%CV,然后是第二行,依此类推
我希望无论表有多少列,它都能工作
我可以用几行代码来实现这一点:
col1 col2 col3
0 100 99 101
1 198 200 202
2 495 500 505
3 600 594 606
4 50 100 150
输出:
df_shape = df.shape
CV_list = []
for i in range(df_shape[0]):
CV = np.std(df.iloc[i, :], ddof=1) / np.mean(df.iloc[i, :]) * 100
CV_list.append(str(round(CV, 3)) + ' %')
df["cv"] = CV_list
df
但是我想知道Pandas是否有用于此的内置函数(我目前还没有找到)。您可以通过指定
axis=1来跨整行操作。因此,得到标准偏差和平均值(每行)的系列,然后除以
col1 col2 col3 CV
0 100 99 101 1%
1 198 200 202 1%
2 495 500 505 1%
3 600 594 606 1%
4 50 100 150 50%
太神了我知道有一个更简单的方法:)非常感谢!
df['CV'] = df.std(axis=1, ddof=1)/df.mean(axis=1)*100
col1 col2 col3 CV
0 100 99 101 1.0
1 198 200 202 1.0
2 495 500 505 1.0
3 600 594 606 1.0
4 50 100 150 50.0