在熊猫数据框中随机插入NA的值

发布于 2021-01-29 16:01:52

如何np.nan在DataFrame中随机插入?假设我要在DataFrame中使用10%的空值。

我的数据如下所示:

df = pd.DataFrame(np.random.randn(5, 3), 
                  index=['a', 'b', 'c', 'd', 'e'],
                  columns=['one', 'two', 'three'])

        one       two     three
a  0.695132  1.044791 -1.059536
b -1.075105  0.825776  1.899795
c -0.678980  0.051959 -0.691405
d -0.182928  1.455268 -1.032353
e  0.205094  0.714192 -0.938242

有没有简单的方法可以插入空值?

关注者
0
被浏览
52
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    这是一种清除10%的单元格的方法(或者说,清除现有数据帧大小所能达到的接近10%)。

    import random
    ix = [(row, col) for row in range(df.shape[0]) for col in range(df.shape[1])]
    for row, col in random.sample(ix, int(round(.1*len(ix)))):
        df.iat[row, col] = np.nan
    

    这是一种以10%的单元格概率独立清除单元格的方法。

    df = df.mask(np.random.random(df.shape) < .1)
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看