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

前端 未结 9 1231
难免孤独
难免孤独 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条回答
  •  孤城傲影
    2020-11-27 20:07

    Here is a one line solution:

    [row[row.first_valid_index()] if row.first_valid_index() else None for _, row in df.iterrows()]
    

    Edit:

    This solution iterates over rows of df. row.first_valid_index() returns label for first non-NA/null value, which will be used as index to get the first non-null item in each row.

    If there is no non-null value in the row, row.first_valid_index() would be None, thus cannot be used as index, so I need a if-else statement.

    I packed everything into a list comprehension for brevity.

提交回复
热议问题