【问题标题】:pandas fill only group meeting criteria?熊猫只填写小组会议标准?
【发布时间】:2020-10-09 03:53:04
【问题描述】:

如何仅填充数据框中不完全为空的组?

在下面的数据框中,只有 df.A=bdf.A=c 的组应该被填充。

df
     A    B
0    a    NaN
1    a    NaN
2    a    NaN
3    a    NaN
4    b    4.0
5    b    NaN
6    b    6.0
7    b    6.0
8    c    7.0
9    c    NaN
10   c    NaN

当时的想法是: if set(df[df.A==(need help here)].B.values) == {np.nan}:.

【问题讨论】:

    标签: python pandas data-science data-cleaning


    【解决方案1】:

    我们可以groupby

    df.B=df.groupby('A').B.apply(lambda x : x.ffill().bfill())
    

    【讨论】:

    • 那是正常填充,但是你如何检查该组在该列中是否不是 nan-only?
    • @DanielB 它会检查,如果都是 NaN ,则没有什么可填充的
    【解决方案2】:

    获取不完全为空的索引,然后在这些索引上forwardfill/backwardfill

    df = df.set_index("A")
    
    #get index where entries in B are not completely full
    ind = df.loc[df.groupby("A").B.transform(lambda x: x.eq(x))].index.unique()
    
    df.loc[ind] = df.loc[ind].ffill().bfill()
    
    
    print(df)
    
         B
    A   
    a   NaN
    a   NaN
    a   NaN
    a   NaN
    b   4.0
    b   4.0
    b   6.0
    b   6.0
    c   7.0
    c   7.0
    c   7.0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 2014-03-26
      • 1970-01-01
      • 2017-03-15
      • 2017-04-06
      相关资源
      最近更新 更多