考虑以下可变长度的2D数组
[
[1, 2, 3],
[4, 5],
[6, 7, 8, 9]
]
如何找到列中变量的平均值?
我想要像[(1 4 6)/ 3,(2 5 7)/ 3,(3 8)/ 2,9 / 1这样的东西
所以最终的结果是[3.667,4.667,5.5,9]
这可能是使用numpy吗?
我试过np.mean(x,axis = 0),但numpy期望相同维度的数组.
现在,我正在弹出每列的元素并找到平均值.有没有更好的方法来实现结果?
解决方法:
你可以使用熊猫:
import pandas as pd
a = [[1, 2, 3],
[4, 5],
[6, 7, 8, 9]]
df = pd.DataFrame(a)
# 0 1 2 3
# 0 1 2 3 NaN
# 1 4 5 NaN NaN
# 2 6 7 8 9
df.mean()
# 0 3.666667
# 1 4.666667
# 2 5.500000
# 3 9.000000
# dtype: float64
这是另一种只使用numpy的解决方案:
import numpy as np
nrows = len(a)
ncols = max(len(row) for row in a)
arr = np.zeros((nrows, ncols))
arr.fill(np.nan)
for jrow, row in enumerate(a):
for jcol, col in enumerate(row):
arr[jrow, jcol] = col
print np.nanmean(arr, axis=0)
# array([ 3.66666667, 4.66666667, 5.5 , 9. ])
标签:python,arrays,numpy
来源: https://codeday.me/bug/20190722/1502199.html