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

问题描述 投票:0回答:3

如何在 DataFrame 中随机插入

np.nan
? 假设我希望 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

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

python pandas numpy missing-data
3个回答
39
投票

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

17
投票

您可以轻松地迭代数据框列,并将

NaN
值分配给
pandas.DataFrame.sample()
方法生成的每个单元格。

代码如下。

for col in df.columns:
    df.loc[df.sample(frac=0.1).index, col] = np.nan

0
投票

稍微添加和修改@Jaroslav Bezděk 的代码,这是我的观点。在这里,我假设您想要将 NaN 应用于数值变量。

# select only numeric columns to apply the missingness to
cols_list = df.select_dtypes('number').columns.tolist()
        
# randomly remove cases from the dataframe
for col in df[cols_list]:
    df.loc[df.sample(frac=0.05).index, col] = np.nan

注意:如果您使用

pd.np.nan
,您会得到
ipython-input-5-e9827aa92133>:9: FutureWarning: The pandas.np module is deprecated and will be removed from pandas in a future version. Import numpy directly instead.

© www.soinside.com 2019 - 2024. All rights reserved.