连续平均正数 [英] Average positive numbers in a row

查看:81
本文介绍了连续平均正数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a numpy matrix, and each row has a combination of positive and negative numbers.

我想创建一个新的向量,该向量为我提供矩阵中一行中所有正数的平均值.

I want to create a new vector, that gives me the average of all the positive numbers in a row in the matrix.

例如,如果这是矩阵:

[[1 2 3 -1]

[2 5 -6 5]]

我想用以下值创建向量:

I want to create the vector with the values:

[[2]

[4]]

最快的方法是什么?

总会有正数.

推荐答案

如果保证每行至少有一个正数(>=0),则可以使用negative numbers (excluding 0)转换为NaNs http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html"rel =" nofollow> np.where ,然后使用

If it's guaranteed to have at least one positive number (>=0) per row, you could convert the negative numbers (excluding 0) to NaNs with np.where and then use np.nanmean along the rows, like so -

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

样品运行-

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

这篇关于连续平均正数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆