2016-08-20 75 views
4

如何随机将np.nan的值插入到DataFrame中? 假设我想在我的DataFrame中使用10%的空值。随机将NA的值插入到熊猫数据框中

我的数据是这样的:

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 

是否有一个简单的方法来插入空值?

回答

6

这里有一种方法可以精确地清除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)