【问题标题】:Merge columns with NaN使用 NaN 合并列
【发布时间】:2018-06-21 18:50:06
【问题描述】:

我正在尝试在 Pandas 中清理一个非常大的数据框。

我有标记为 currentAge、currentAge2、sex、sex2、height、height2、weight、weight2 的列。对于某些行,currentAge 有一个值,而对于其他行,currentAge2 有一个 NaN。它也可以采用另一种方式,对于某些行,currentAge2 有一个值,currentAge 有一个 NaN。其他指标性别、体重和身高也是如此。

我想将常用指标合并在一起,如 currentAge 和 currentAge2,以便有一列 currentAge 没有 NaN。

我该怎么做呢?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您需要使用fillna。让我们考虑一下这个数据框,其中一些年龄在 currentAge 列中,而另一些在 currentAge2 列中:

    df = pd.DataFrame({'currentAge':[np.nan, 12, 15, 16, np.nan], 
                       'currentAge2':[8, np.nan, np.nan, np.nan, 24]})
       currentAge  currentAge2
    0         NaN          8.0
    1        12.0          NaN
    2        15.0          NaN
    3        16.0          NaN
    4         NaN         24.0
    

    然后你可以做的是:df['currentAge'] = df['currentAge'].fillna(df['currentAge2']) 用第二列中的值填充第一列中的所有nan,然后你得到:

       currentAge  currentAge2
    0         8.0          8.0
    1        12.0          NaN
    2        15.0          NaN
    3        16.0          NaN
    4        24.0         24.0
    

    要删除 currentAge2 列,然后执行df = df.drop('currentAge2',1),您将填充一个简单的 currentAge 列。

    【讨论】:

    • 就是这样。非常感谢。我会赞成并批准这个答案。
    猜你喜欢
    • 2019-11-25
    • 2021-09-20
    • 2022-08-16
    • 1970-01-01
    • 2022-01-22
    • 2014-05-12
    • 1970-01-01
    • 2017-08-08
    • 2023-01-23
    相关资源
    最近更新 更多