首页 > 解决方案 > 设置一定百分比的数据帧等于 NaN

问题描述

我想将随机数据帧值设置为等于 NaN 以获得一定百分比的 NaN。所以从以下数据框:

     name                       IS_030_EBITDA  IS_09_PostTaxResult
0    EISMA MEDIA GROEP B.V.     NaN            1292.0
1    EISMA MEDIA GROEP B.V.     2280.0         1324.0
2    DUNLOP B.V.                43433.0        1243392.0
3    DUNLOP B.V.                2243480.0      1324.0

我希望我的 Dataframe 恰好有 25% 的值等于 NaN(下面的 NaN 只是一个示例,必须随机完成):

     name                       IS_030_EBITDA  IS_09_PostTaxResult
0    EISMA MEDIA GROEP B.V.     NaN            1292.0
1    EISMA MEDIA GROEP B.V.     2280.0         1324.0
2    DUNLOP B.V.                43433.0        NaN
3    DUNLOP B.V.                2243480.0      1324.0

所以重要的是要理解我不想将 25% 的行或列设置为 NaN,我希望在我的最终数据框中有 25% 的值等于 NaN。

感谢您的帮助。

标签: pythonpandasdataframe

解决方案


你想做这样的事情吗?:

# modified the data to make it read_clipboard friendly
'''
    name    IS_030_EBITDA   IS_09_PostTaxResult
0    EISMA_MEDIA_GROEP_B.V. NaN 1292.0
1    EISMA_MEDIA_GROEP_B.V. 2280.0  1324.0
2    DUNLOP_B.V.    43433.0 1243392.0
3    DUNLOP_B.V.    2243480.0   1324.0
'''

df = pd.read_clipboard()

print(df)

df_sample=df.sample(2) # refer to the 'Note' section below
df_sample[['IS_09_PostTaxResult', 'IS_030_EBITDA']]='NaN'
df.update(df_sample)

print(df)

.

df 原文:

                     name  IS_030_EBITDA  IS_09_PostTaxResult
0  EISMA_MEDIA_GROEP_B.V.            NaN               1292.0
1  EISMA_MEDIA_GROEP_B.V.         2280.0               1324.0
2             DUNLOP_B.V.        43433.0            1243392.0
3             DUNLOP_B.V.      2243480.0               1324.0

df修改:

                     name IS_030_EBITDA IS_09_PostTaxResult
0  EISMA_MEDIA_GROEP_B.V.           NaN                 NaN
1  EISMA_MEDIA_GROEP_B.V.          2280                1324
2             DUNLOP_B.V.         43433         1.24339e+06
3             DUNLOP_B.V.           NaN                 NaN

笔记:

“df_sample=df.sample(2)” -> 您可以添加一个逻辑来选择总样本记录的 25% 并替换值 2。示例:

# 25% data in each column 
x=25.0
factor = int((len(df)*x)/100) # factor=1 in the example above

df_sample=df.sample(factor)

推荐阅读