mercredi 31 janvier 2018

Counting values in a row that match a condition - Python

I have a dataframe that contains integers and NaNs. I am almost looking to create a countif statement, which will iterate over each value in a row and count values that are greater than 0.

Here is an example df:

d = {'col1': [1, "", 5, 0], 'col2': [3, 4, "", 7], 'col3': [2, 8, "", 3]}
df = pd.DataFrame(data=d)
df = df.convert_objects(convert_numeric = True)

df
Out[356]: 
col1  col2  col3
0   1.0   3.0   2.0
1   NaN   4.0   8.0
2   5.0   NaN   NaN
3   0.0   7.0   3.0

I have been using this function below that counts values that are not NaNs, however I want to place a condition on this (greater than 0 & not NaN).

df.apply(lambda x: x.count(), axis = 1)
Out[357]: 
0    3
1    2
2    1
3    3
dtype: int64

If anyone could offer advice on how to count values in a row based on a certain condition that would be very useful, thanks in advance.

Aucun commentaire:

Enregistrer un commentaire