管理数据框中的随机Nan值

时间:2019-02-28 17:22:46

标签: python pandas dataframe

更新: 考虑到起始数据中已经有空值,我希望将NaN值随机管理到我的每一列的数据集中。

起初,我必须为我的数据中的每列计算NaN值比率:

{'A': 0.1, 'B': 0.0, 'C': 0.47, 'D': 0.0, 'E': 0.41, 'F': 0.0}

现在我想按列向上随机输入NaN值:

“ nan_percent”:

{'A': 0.15, 'B': 0.0, 'C': 0.9, 'D': 0.5, 'E': 0.41, 'F': 0.2}

我为什么要这样做?是为了让数据看起来更像我的学习问题的现实。

我尝试此代码:

df = df.mask(np.random.choice([True, False], size=df.shape, p= nan_percent))

我有一个错误:

TypeError: float() argument must be a string or a number, not 'dict'

如何通过dict“ nan_percent”随意管理每列正确的nan值百分比?

3 个答案:

答案 0 :(得分:0)

我们可以为每一列运行以下代码:

target = 0.5
col = "Big"
difference = int(target * len(df[col]) - df[col].isnull().sum())
while(difference!=0):
    num = np.random.randint(0, len(col))%len(col)
    if df.loc[num, col] == np.NaN:
        continue
    else:
        df.loc[num, col] = np.NaN
        difference = difference - 1

答案 1 :(得分:0)

尝试这种方式:

string separator

答案 2 :(得分:0)

在执行此操作时:我想您希望尺寸为100

nan_percent_per_column = {'A': 0.15, 'B': 0.23, 'C': 0.10}

#create empty DF with columns names for the test
df = pd.DataFrame(columns=['A', 'B', 'C'])
for col in df.columns:
    p = nan_percent_per_column[col]
    df[col] = np.random.choice(a=[np.nan, ''], size=100, p=[p, 1 - p])

print(df)

如果您已经填写了X列,则可以使用size=df['X'].shape

相关问题