python numpy ndarray element-wise mean

2020-03-08 08:08发布

问题:

I'd like to calculate element-wise average of numpy ndarray.

In [56]: a = np.array([10, 20, 30])

In [57]: b = np.array([30, 20, 20])

In [58]: c = np.array([50, 20, 40])

What I want:

[30, 20, 30]

Is there any in-built function for this operation, other than vectorized sum and dividing?

回答1:

You can just use np.mean directly:

>>> np.mean([a, b, c], axis=0)
array([ 30.,  20.,  30.])


回答2:

Pandas DataFrames have built in operations to get column and row means. The following code may help you:

import pandas and numpy
import pandas as pd
import numpy as np

# Define a DataFrame
df = pd.DataFrame([
np.arange(1,5), 
np.arange(6,10),
np.arange(11,15)
])

# Get column means by adding the '.mean' argument
# to the name of your pandas Data Frame
# and specifying the axis

column_means = df.mean(axis = 0)

'''
print(column_means)

0    6.0
1    7.0
2    8.0
3    9.0
dtype: float64
'''   

# Get row means by adding the '.mean' argument
# to the name of your pandas Data Frame
# and specifying the axis

row_means = df.mean(axis = 1)
'''
print(row_means)

0     2.5
1     7.5
2    12.5
dtype: float64
'''