pandas 随机替换k% [英] pandas randomly replace k percent

查看:59
本文介绍了 pandas 随机替换k%的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有一个简单的熊猫数据框,其中包含2列idvalue,其中value01,我想用0随机替换所有value==110%.

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
  • 即可过滤df
  • 使用sample(frac=.1)占其中的10%
  • 使用结果索引分配零
  • use query to get filtered df with only value == 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'] is 1
  • 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆