如何在空值上折叠 pandas 中的列? [英] how to collapse columns in pandas on null values?

查看:58
本文介绍了如何在空值上折叠 pandas 中的列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下数据框:

pd.DataFrame({'col1':    ["a", "a", np.nan, np.nan, np.nan],
            'override1': ["b", np.nan, "b", np.nan, np.nan],
            'override2': ["c", np.nan, np.nan, "c", np.nan]})


    col1    override1   override2
0     a        b          c
1     a       NaN        NaN
2     NaN      b         NaN
3     NaN     NaN         c
4     NaN     NaN         NaN

有没有一种方法可以将3列折叠为一列,其中 override2 会覆盖 override1 ,它会覆盖 col1 ,但是,如果存在NaN,则必须保留bofore的值?另外,我主要是在寻找一种无需增加额外专栏的方法。我真的在寻找内置的熊猫解决方案。

Is there a way to collapse the 3 columns into one column, where override2 overrides override1, which overrides col1, however, in case there is NaN, then the values bofore is to be kept? Also, I am mainly looking for a way where I would not have to make an additional column. I am really looking for a built-in pandas solution.

这是我正在寻找的输出:

This is the output I am looking for:

 collapsed
0  c
1  a
2  b
3  c
4  NaN


推荐答案

使用填充

df.ffill(1).iloc[:,-1]

这篇关于如何在空值上折叠 pandas 中的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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