英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论