【问题标题】:Pandas - Replace NaN with two different valuesPandas - 用两个不同的值替换 NaN
【发布时间】:2016-09-23 13:11:24
【问题描述】:

我正在尝试替换我的 DataFrame 中的 NaN 值。 我想用一个值替换 60% 的 NaN,用另一个值替换 40%。 我阅读了 fillna 方法的文档,但没有找到。

有什么想法吗?

谢谢

【问题讨论】:

  • 在提问时尽量提供Minimal, Complete, and Verifiable example。如果有 pandas 问题,请提供示例 input 和 output 数据集(CSV/dict/JSON/Python 代码格式的 5-7 行 作为文本,因此可以在为您编写答案时使用它)。这将有助于避免以下情况:your code isn't working for me 或it doesn't work with my data 等。

标签: python pandas scikit-learn


【解决方案1】:

你可以这样做:

df.loc[your_condition_for_60%] = df.fillna(10)
df.loc[your_condition_for_40%] = df.fillna(20)

【讨论】:

    【解决方案2】:

    创建一个布尔数组,该数组有可能是 60/40 True/False,大小与您要填充的 df 相同。然后使用combine_first

    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame(index=list('ABCDEFGHIJ'), columns=list('abcdefghij'))
    
    mask60 = np.random.rand(*df.shape) > 0.6
    
    value40, value60 = 10, 20
    
    fill = value60 * mask60 + value40 * (1 - mask60)
    
    fill = value40 + mask60 * (value60 - value40)
    
    fill_df = pd.DataFrame(fill, index=df.index, columns=df.columns)
    

    看起来像:

    print df.combine_first(fill_df)
    
        a   b   c   d   e   f   g   h   i   j
    A  10  10  20  20  10  10  10  10  10  20
    B  10  10  10  10  10  20  20  10  10  10
    C  20  10  10  10  10  10  10  20  20  20
    D  10  10  10  20  10  10  20  10  10  10
    E  20  20  10  10  20  10  10  10  20  10
    F  10  20  10  10  20  10  20  10  10  20
    G  20  20  10  10  10  10  10  20  20  10
    H  10  10  20  20  10  10  10  10  10  10
    I  10  10  10  20  20  10  10  10  10  20
    J  10  10  10  20  10  10  20  10  10  10
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-23
      • 2018-11-14
      • 2021-09-24
      • 2021-03-08
      • 1970-01-01
      • 2022-07-06
      • 2017-07-04
      相关资源
      最近更新 更多