用偶数和奇数列计算熊猫的均值

时间:2019-01-19 16:41:24

标签: python python-3.x pandas mean

假设我有这个数据框:

df = pd.DataFrame({'col1': [1, 2, 3, 4, 5], 
              'col2': [7, 45, 12, 56, 14],
              'col3': [56, 67, 8, 12, 39],
              'col4': [16, np.nan, 25, 6, 19],
              'col5': [1, 9, 23, 56, np.nan],
              'col6': [13, 3, 53, 72, 88]})

我只想计算此数据帧的偶数列和奇数列的均值。我已经尝试过以下代码:

df['avg_odd'] = df[[df.columns[0],df.columns[2],df.columns[4]]].mean(axis=1)
df['avg_even'] = df[[df.columns[1],df.columns[3],df.columns[5]]].mean(axis=1)

但是有什么办法可以更快地做到吗?如果我有100列或更多列,应该如何计算?

3 个答案:

答案 0 :(得分:5)

使用 69%] Linking CXX shared library libTsmToLfsResponseEncoderd.so [ 92%] Built target TsmToLfsResponseEncoder [100%] Linking CXX executable LFsToTsm-externalEntity-test ../.../libTsmToLfsResponseEncoderd.so: undefined reference to `converter::tsmToLfsResponseEncoder::EntityDecoder::buffer' } %

groupby

df[['avg_odd', 'avg_even']] = df.groupby(np.arange(df.shape[1]) % 2, axis=1).mean()

答案 1 :(得分:3)

按模数长度按列长度创建帮助程序并创建新列:

arr = np.arange(len(df.columns)) % 2

df['avg_odd']  = df.iloc[:, arr == 0].mean(axis=1)
df['avg_even'] = df.iloc[:, arr == 1].mean(axis=1)

print (df)
   col1  col2  col3  col4  col5  col6    avg_odd   avg_even
0     1     7    56  16.0   1.0    13  19.333333  12.000000
1     2    45    67   NaN   9.0     3  26.000000  24.000000
2     3    12     8  25.0  23.0    53  11.333333  30.000000
3     4    56    12   6.0  56.0    72  24.000000  44.666667
4     5    14    39  19.0   NaN    88  22.000000  40.333333

答案 2 :(得分:3)

df = df.assign(avg_even = df[df.columns[::2]].mean(axis=1),
               avg_odd = df[df.columns[1::2]].mean(axis=1))

简单直接