SoFunction
Updated on 2024-11-10

Python to find the average value of array by column non-zero elements in numpy case

Input: numpy's array

Output: a one-dimensional array of averages

import numpy as np
 
def non_zero_mean(np_arr):
 exist = (np_arr != 0)
 num = np_arr.sum(axis=1)
 den = (axis=1)
 return num/den

If you want to average the non-zero elements by row, change all axis=1 to axis=0.

Additional knowledge:python dataframe counts the number of zeros in a row and column

1, by line statistics, return to a series:

(df == 0).astype(int).sum(axis=1)

Above this python seek numpy in array by column non-zero elements of the average value of the case is all I share with you, I hope to give you a reference, but also hope that you support me more.