pandas 随机替换k% [英] pandas randomly replace k percent
本文介绍了 pandas 随机替换k%的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
具有一个简单的熊猫数据框,其中包含2列id
和value
,其中value
是0
或1
,我想用0
随机替换所有value==1
的10%
.
having a simple pandas data frame with 2 columns e.g. id
and value
where value
is either 0
or 1
I would like to randomly replace 10%
of all value==1
with 0
.
如何用熊猫来实现这种行为?
How can I achieve this behaviour with pandas?
推荐答案
pandas
答案
- 使用
query
仅使用value == 1
即可过滤 - 使用
sample(frac=.1)
占其中的10% - 使用结果索引分配零
df
- use
query
to get filtereddf
with onlyvalue == 1
- use
sample(frac=.1)
to take 10% of those - use the index of the result to assign zero
df.loc[
df.query('value == 1').sample(frac=.1).index,
'value'
] = 0
替代numpy
答案
alternative numpy
answer
- 获取
df['value']
为1
的布尔数组
- 分配10%的零和90%的随机数组
- get boolean array of where
df['value']
is1
- assign random array of 10% zeros and 90% ones
v = df.value.values == 1
df.loc[v, 'value'] = np.random.choice((0, 1), v.sum(), p=(.1, .9))
这篇关于 pandas 随机替换k%的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文