Python 如何基于其他列的平均值创建的多个列
我想要包含前几列平均值的列。Python 如何基于其他列的平均值创建的多个列,python,pandas,Python,Pandas,我想要包含前几列平均值的列。 e、 g.对于以下数据帧: Col1 Col2 Col3 Col4 Col5 ... ColN Row1 5 6 9 10 9 ... 10 Row2 4 7 4 0 9 ... 8 Row3 4 8 3 1 7 ... 5 我想循环这个,所以我创建了列“Avg_2_4”、“Avg_3_5”
e、 g.对于以下数据帧:
Col1 Col2 Col3 Col4 Col5 ... ColN
Row1 5 6 9 10 9 ... 10
Row2 4 7 4 0 9 ... 8
Row3 4 8 3 1 7 ... 5
我想循环这个,所以我创建了列“Avg_2_4”、“Avg_3_5”,一直到“Avg_N-2_N”
我可以使用下面的代码得到Col1到Col3的平均值
col = df.loc[:,"Col1":"Col3"]
df["Avg_1_3"] = col.mean(axis=1)
我相信下面给出的例子会解决你的问题
import pandas as pd
import numpy as np
cols = 4
rows = 10
# Sample Data Creation
df = pd.DataFrame()
for i in range(1,cols+1):
df['Col'+str(i)] = np.random.randint(0,10,rows)
# Column wise rolling mean calculation with a window of 3
avg = df.rolling(window=3, axis=1).mean()
# Assinging appropriate column names to calculated mean df's columns
avg_cols = pd.Series(range(1,cols+1)).astype(str)
avg_cols = 'Avg_' + avg_cols.shift(2) + '_' + avg_cols
avg.columns = avg_cols
# merging the results
df = pd.concat([df,avg.dropna(axis=1)], axis=1)
df.滚动(3,轴=1).mean()
?