0

I have the following dataframe:

df
   id grp1 grp2
0   1    a  NaN
1   2    b    d

I need to create a new column with count of values from grp1 and grp2 columns.Something like below

df
   id grp1 grp2 grp_count
0   1    a  NaN      1
1   2    b    d      2

One way of achieving this is using pandas apply with a function to get the count iterating row by row which will affect the performance.

Is there a way we can do it without using pandas apply?

0

1 Answer 1

2

Pandas DataFrame count method ignores nan values by default, therefore:

df['grp_count'] = df[['grp1', 'grp2']].count(axis=1)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.