First column name with non null value by row pandas

前端 未结 3 2146
青春惊慌失措
青春惊慌失措 2021-01-03 08:59

I want know the first year with incoming revenue for various projects.

Given the following, dataframe:

ID  Y1      Y2      Y3
0   NaN     8       4
1         


        
3条回答
  •  借酒劲吻你
    2021-01-03 09:35

    You can apply first_valid_index to each row in the dataframe using a lambda expression with axis=1 to specify rows.

    >>> df.apply(lambda row: row.first_valid_index(), axis=1)
    ID
    0      Y2
    1      Y3
    2    None
    3      Y1
    dtype: object
    

    To apply it to your dataframe:

    df = df.assign(first = df.apply(lambda row: row.first_valid_index(), axis=1))
    
    >>> df
        Y1  Y2  Y3 first
    ID                  
    0  NaN   8   4    Y2
    1  NaN NaN   1    Y3
    2  NaN NaN NaN  None
    3    5   3 NaN    Y1
    

提交回复
热议问题