如果我在Pandas中有一个DataFrame,看起来像这样:
A B C
0 1 NaN 2
1 NaN 3 NaN
2 NaN 4 5
3 NaN NaN NaN
如何从每一行中获取第一个非空值?例如,上面我想得到:([1, 3, 4, None]
或等效的Series)。
这是一种非常麻烦的方法,首先用于first_valid_index
获取有效列,将返回的序列转换为数据框,以便我们可以apply
逐行调用并将其用于索引回原始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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句