Ashwin Jayarama
Ashwin Jayarama

Reputation: 261

How to count the values of columns row wise based on conditions in Pandas

I have a pandas dataframe df below

df = pd.DataFrame({'id':[1,2,3],'v' : ['r','r','i'], 'w' : ['r','r','i'],'x' : ['r','i','i']})
df

id v  w  x
1  r  r  r
2  r  r  i
3  i  i  i

The values of columns are r and i. I want to count the occurrences of r and i row wise and generate two more colum headers r and i with the counts of r and i` as values for each row, the final result I am expecting is given below

id v  w  x r i
1  r  r  r 3 0
2  i  r  r 2 1
3  i  i  i 0 3

Upvotes: 5

Views: 2883

Answers (1)

Nader Hisham
Nader Hisham

Reputation: 5414

Method 1


In [15]:
def count(df):
    df['i'] = np.sum(df == 'i')
    df['r'] = np.sum(df == 'r')
    return df

In [16]:
df.apply(count, axis = 1)
Out[16]:
    id  v   w   x   i   r
0   1   r   r   r   0   3
1   2   r   r   i   1   2
2   3   i   i   i   3   0

Method 2


In [9]:
count = df.apply(lambda x : x.value_counts() , axis = 1)[['i' , 'r']]
count
Out[9]:
    i   r
0   NaN 3
1   1   2
2   3   NaN

In [10]:
pd.concat([df , count.fillna(0)] , axis = 1)
Out[10]:
    id  v   w   x   i   r
0   1   r   r   r   0   3
1   2   r   r   i   1   2
2   3   i   i   i   3   0

Upvotes: 4

Related Questions