【问题标题】:Fill NaNs in dataframe with different numbers用不同的数字填充数据框中的 NaN
【发布时间】:2022-01-14 10:30:34
【问题描述】:

我有一个 df:

df = pd.DataFrame({'Col1': [np.NaN, 1, 2], 'Col2': [7, 9, np.NaN], 'Col3': [np.NaN, np.NaN, 5]})

如何将df 中的每个 NaN 替换为 df 中不存在的随机唯一数字,例如:

df = pd.DataFrame({'Col1': [8, 1, 2], 'Col2': [7, 9, 11], 'Col3': [30, 33, 5]})

非常感谢。

【问题讨论】:

    标签: python pandas replace nan


    【解决方案1】:

    一种方法是用 df 屏蔽相同大小的随机数:

    import random
    total_size = df.shape[0]*df.shape[1]
    rands = [x for x in random.sample(range(total_size*10), total_size*2) if x not in df.values][:total_size]
    rands_mat = np.array(rands).reshape((df.shape))
    df.mask(pd.isnull(df), rands_mat)
    
    Col1 Col2 Col3
    0 4 7 23
    1 1 9 19
    2 2 71 5

    【讨论】:

    • 它有效。非常感谢:)
    猜你喜欢
    • 2022-01-07
    • 2018-12-20
    • 2021-01-20
    • 1970-01-01
    • 2014-03-15
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 2020-06-27
    相关资源
    最近更新 更多