gpt4 book ai didi

python:可变长度2矩阵的平均值

转载 作者:太空宇宙 更新时间:2023-11-03 12:45:12 24 4
gpt4 key购买 nike

考虑以下可变长度二维数组

[
[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 需要相同维度的数组。

现在,我正在弹出每列的元素并找到平均值。有没有更好的方法来实现这个结果?

最佳答案

你可以使用 Pandas :

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:可变长度2矩阵的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40225870/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com