First non-null value per row from a list of Pandas columns

前端 未结 9 1247
难免孤独
难免孤独 2020-11-27 19:23

If I\'ve got a DataFrame in pandas which looks something like:

    A   B   C
0   1 NaN   2
1 NaN   3 NaN
2 NaN   4   5
3 NaN NaN NaN

How ca

9条回答
  •  猫巷女王i
    2020-11-27 20:11

    groupby in axis=1

    If we pass a callable that returns the same value, we group all columns together. This allows us to use groupby.agg which gives us the first method that makes this easy

    df.groupby(lambda x: 'Z', 1).first()
    
         Z
    0  1.0
    1  3.0
    2  4.0
    3  NaN
    

    This returns a dataframe with the column name of the thing I was returning in my callable


    lookup, notna, and idxmax

    df.lookup(df.index, df.notna().idxmax(1))
    
    array([ 1.,  3.,  4., nan])
    

    argmin and slicing

    v = df.values
    v[np.arange(len(df)), np.isnan(v).argmin(1)]
    
    array([ 1.,  3.,  4., nan])
    

提交回复
热议问题