将 pandas 系列中的值根据条件设置为随机值。

huangapple go评论78阅读模式
英文:

Set values in pandas series to a random value based on condition

问题

nums = np.random.choice(range(100, 1100), size=924)
df.loc[df['Target'] == 0, 'Target'] = nums
英文:

I have a pandas series, and I'd like to set all the values that are 0 to a random number between 100 and 1000. Is there a direct way of doing that? I've only seen a roundabout way like so:

nums = np.random.choice(range(100, 1100), size = 924)

df.loc[df['Target']==0] = nums

The error I get back here is "Must have equal len keys and value when setting with an iterable".

Size is 924 because I know that's how many values I want to change.

答案1

得分: 1

"Would row by row suffice?"

如果逐行进行是否足够
import random
df.Target = df.Target.apply(lambda x: random.randint(1, 1000) if x == 0 else x)

"If the row's value in Target is 0, then generate a random number, else just return what's already there."

如果目标列中的行值为`0`,则生成随机数否则返回已有的值
英文:

Would row by row suffice?

import random
df.Target = df.Target.apply(lambda x: random.randint(1, 1000) if x == 0 else x)

If the row's value in Target is 0, then generate a random number, else just return what's already there.

答案2

得分: 1

你只需指定列也是如此。将最后一行改为:

df.loc[df['Target']==0, 'Target'] = nums

英文:

You just have to specify the column as well. Switch the last line to

df.loc[df['Target']==0, 'Target'] = nums

huangapple
  • 本文由 发表于 2023年4月19日 16:06:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76052099.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定