Get count unique values in a row in pandas

前端 未结 4 1475
悲&欢浪女
悲&欢浪女 2021-01-22 19:57

Suppose I have the following data frame:

0     1        2
new   NaN      NaN
new   one      one
a     b        c
NaN   NaN      NaN

How would I

4条回答
  •  再見小時候
    2021-01-22 20:42

    It is not as fast as coldspeed's answer with set(), but you could also do

    df['_num_unique_values'] = df.T.nunique()
    

    First the transpose of df dataframe is taken with df.T and then nunique() is used to get the count of unique values excluding NaNs.

    This is added as a new column to the original dataframe.

    df would now be

        0   1   2   _num_unique_values
    0   new nan nan 1
    1   new one one 2
    2   a   b   c   3
    3   nan nan nan 0
    

提交回复
热议问题