代码之家  ›  专栏  ›  技术社区  ›  Josh Friedlander

循环几个值以填充数据帧中的NAN

  •  1
  • Josh Friedlander  · 技术社区  · 6 年前

    documentation 对于 fillna

    np.random.seed(0)
    s = pd.Series(np.random.randint(0,100, 50))
    s.loc[s > 25] = np.nan
    s.fillna([10, 20, 30]) # Produces TypeError 
    

    0   10
    1   20
    2   30
    3   10
    4   20
    5   9.0
    6   30
    7   21.0
    8   10
    

    这不是因为很难矢量化而内置的吗?值得一提的是,这只是理论上的,我没有实际数据。

    2 回复  |  直到 6 年前
        1
  •  2
  •   BENY    6 年前

    使用

    s.loc[s.isna()]=[10,20,30]*(s.isna().sum()//3)+[10,20,30][:s.isna().sum()%3]
    s
    Out[271]: 
    0     10.0
    1     20.0
    2     30.0
    3     10.0
    4     20.0
    5      9.0
    6     30.0
    ...
    
        2
  •  1
  •   jpp    6 年前

    不需要将值转换为 NaN

    np.random.seed(0)
    s = pd.Series(np.random.randint(0,100, 50))
    

    loc np.resize :

    mask = s > 25
    s.loc[mask] = np.resize([10, 20, 30], mask.sum())
    

    pd.Series.mask

    s = s.mask(s > 25, np.resize([10, 20, 30], len(s.index)))
    

    结果:

    print(s.head(10))
    # 0    10
    # 1    20
    # 2    30
    # 3    10
    # 4    20
    # 5     9
    # 6    30
    # 7    21
    # 8    10
    # 9    20
    # dtype: int32