简体   繁体   English

如何通过从列表中随机选择元素来替换数据框中的值?

[英]How to replace values in dataframe by choosing elements from list at random?

I have a dataframe with 1's and 0's which looks like:我有一个带有 1 和 0 的数据框,它看起来像:

Index Variable_1 Variable_2 Variable_3
A     1          0          1
B     0          1          1
C     0          0          1

I also have a list which looks like: {'X','Y','Z'}我还有一个列表,看起来像:{'X','Y','Z'}

I want to replace all '1's in the dataframe with values from the list at random.我想用列表中的值随机替换数据框中的所有“1”。 So the output could look like:所以输出可能如下所示:

Index Variable_1 Variable_2 Variable_3
A     Y          0          X
B     0          Z          Y
C     0          0          Z

How can I achieve this?我怎样才能做到这一点?

you can use np.where and random.choice as你可以使用 np.where 和 random.choice 作为

import random

yourlist = ['X','Y','Z']
df = df.where(df == 1, random.choice(yourlist))

You can also use .replace as您也可以使用 .replace 作为

df = df.replace(1, random.choice(yourlist))

Update: you are right that we have random.choice same for every replacement, it isnt evaluated for all element?更新:你是对的,我们对每个替换都有相同的 random.choice,它没有对所有元素进行评估?

can you try this and see how it works你能试试这个看看它是如何工作的吗

 df = df.update(np.random.choice(yourlist, size=df.shape), filter_func=lambda x: x==1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM