【问题标题】:backward filling with condition反向填充条件
【发布时间】:2017-09-12 20:26:49
【问题描述】:

我想在具有以下条件的数据帧的特定列上应用反向填充:我认为“colum_A”只能假设四个值,称为 A、B、C、D,并且反向填充应该工作如下:

if the first not NaN is A, then backward_filling with A;

if the first not NaN is B, then backward_filling with B;

if the first not NaN is C, then backward_filling with B;

if the first not NaN is D, then backward_filling with C;

if the column_A only contains NaN, then backward_filling with D

例如:

输入 DF:

colum_A
 NaN
 NaN
 B
 B
 C
 C

输出DF:

colum_A
 B
 B
 C
 C
 D
 D

请,任何帮助将不胜感激。 此致, 卡罗

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    我认为你需要 mapbfill 条件:

    #get mask for back filling NaNs
    m = df['colum_A'].isnull()
    d = {'A':'A','B':'B','C':'B','D':'C'}
    #D if all values NaN
    df['colum_B'] = 'D' if m.all() else np.where(m, df['colum_A'].map(d).bfill(),df['colum_A'])
    #alternative
    #df['colum_B'] = 'D' if m.all() else df['colum_A'].mask(m, df['colum_A'].map(d).bfill())
    print (df)
       colum_A colum_B
    0      NaN       B
    1      NaN       B
    2        B       B
    3        A       A
    4      NaN       B
    5        C       C
    6        C       C
    7      NaN       C
    8      NaN       C
    9      NaN       C
    10       D       D
    11       D       D
    12       A       A
    13       C       C
    14     NaN       A
    15       A       A
    16     NaN     NaN
    

    【讨论】:

    • 是的。有效。非常感谢耶斯瑞尔。请您提供更多关于 np.where 在这种特殊情况下的作用的信息吗?
    • 当然,函数numpy.where 像 if else 一样工作,但使用数组。我认为链接希望更多。
    • 太棒了。非常感谢。非常感谢。
    猜你喜欢
    • 2020-08-03
    • 2016-03-18
    • 2020-06-18
    • 2019-10-02
    • 1970-01-01
    • 1970-01-01
    • 2011-05-27
    • 2018-06-27
    • 1970-01-01
    相关资源
    最近更新 更多