Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate mean in pandas with even and odd columns

Suppose that I have this data frame:

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]})

All I want is to calculate mean of even columns and odd columns of this dataframe. I have tried these codes:

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)

But is there any way to do it faster? How should I calculate if I have 100 columns or more?

like image 482
Long_NgV Avatar asked Jan 19 '19 16:01

Long_NgV


3 Answers

Create helper arange by length of columns with modulo and create new columns:

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
like image 169
jezrael Avatar answered Oct 12 '22 21:10

jezrael


Using % and groupby

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

   col1  col2  col3  col4  col5  col6   avg_even    avg_odd
0     1     7    56  16.0   1.0    13  12.000000  19.333333
1     2    45    67   NaN   9.0     3  24.000000  26.000000
2     3    12     8  25.0  23.0    53  30.000000  11.333333
3     4    56    12   6.0  56.0    72  44.666667  24.000000
4     5    14    39  19.0   NaN    88  40.333333  22.000000
like image 21
user3483203 Avatar answered Oct 12 '22 22:10

user3483203


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

Simple and direct

like image 4
Attersson Avatar answered Oct 12 '22 22:10

Attersson