2016-08-20 14 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 

はNULL値を挿入する簡単な方法はありますか?

答えて

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) 
関連する問題