python - 平均连续的正数

标签 python math numpy matrix

我有一个 numpy 矩阵,每一行都有正数和负数的组合。

我想创建一个新向量,它给出矩阵中一行中所有正数的平均值。

例如,如果这是矩阵:

[[1 2 3 -1]

[2 5 -6 5]]

我想用以下值创建向量:

[[2]

[4]]

最快的方法是什么?

总会有正数。

最佳答案

如果保证每行至少有一个正数(>=0),您可以将负数(不包括0)转换为NaN np.where然后使用 np.nanmean沿着行,像这样 -

np.nanmean(np.where(A>=0,A,np.nan),axis=1)

sample 运行-

In [69]: A
Out[69]: 
array([[ 2,  3, -6, -6, -4],
       [-5, -6, -1, -1,  3],
       [-8,  5, -7, -9, -9],
       [-3,  0,  7, -5, -6]])

In [70]: np.nanmean(np.where(A>=0,A,np.nan),axis=1)
Out[70]: array([ 2.5,  3. ,  5. ,  3.5])

关于python - 平均连续的正数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35078420/

相关文章:

python - 从 C 代码调用 numpy 函数

python - 在 Python 中使用 reshape reshape 数组

python - 如何在 pandas dataframe Python 中查找带有分隔符的字符串并将其替换为新行

math - 给定 n 个点之间的距离,如何根据这些关系绘制 map

javascript - 重新校准使用 css 变换的 x 和 y 偏移

algorithm - 将一个随机值分成四个总和

python - python中的list1 = [] list2 = []和list1 = list2 = []有什么区别?

python - matplotlib barplot 的最后一个栏被填充了一半

python - 如果 pandas 数据框中的年份低于 1900,则更改年份

python - Python 十六进制字符串中 0x 和\x 的含义有什么区别?