python - 设置一定百分比的数据帧等于 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。
感谢您的帮助。
解决方案
你想做这样的事情吗?:
# 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)
推荐阅读
- reactjs - Redux 商店不会在第一次单击按钮时更新
- swift - 如何在 Firebase 存储参考观察者中进行计算?
- angular - Angular - 为表单控件中的输入类型编号设置默认值
- tensorflow - 使用 tensorflow 对象检测 api 进行迁移学习
- android - 支持 AppBundle 的标准
- sql - 计算每一步的过程——在SQL中
- linux - 捕获中断时抑制终端输出中的“^C”字符串
- mysql - 我的 sql 查询被中止,但可用磁盘空间没有恢复;为什么?
- .net - 将电子邮件附件保存到 excel 文件会损坏文件
- sql - 将 WHERE 子句添加到带有第三个表中的参数的 JOIN