pandas 列列表中每行的第一个非空值 [英] First non-null value per row from a list of Pandas columns

查看:151
本文介绍了 pandas 列列表中每行的第一个非空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在Pandas中有一个DataFrame,看起来像这样:

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

如何从每一行中获取第一个非空值?例如.对于以上情况,我想获得:[1, 3, 4, None](或等效的Series).

How can I get the first non-null value from each row? E.g. for the above, I'd like to get: [1, 3, 4, None] (or equivalent Series).

推荐答案

这是一种非常麻烦的方法,首先使用first_valid_index获取有效列,将返回的序列转换为数据框,以便我们调用apply按行,并使用它索引回原始df:

This is a really messy way to do this, first use first_valid_index to get the valid columns, convert the returned series to a dataframe so we can call apply row-wise and use this to index back to original df:

In [160]:
def func(x):
    if x.values[0] is None:
        return None
    else:
        return df.loc[x.name, x.values[0]]
pd.DataFrame(df.apply(lambda x: x.first_valid_index(), axis=1)).apply(func,axis=1)
​
Out[160]:
0     1
1     3
2     4
3   NaN
dtype: float64

编辑

一种更简洁的方法:

In [12]:
def func(x):
    if x.first_valid_index() is None:
        return None
    else:
        return x[x.first_valid_index()]
df.apply(func, axis=1)

Out[12]:
0     1
1     3
2     4
3   NaN
dtype: float64

这篇关于 pandas 列列表中每行的第一个非空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆