简体   繁体   中英

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:

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'}

I want to replace all '1's in the dataframe with values from the list at random. 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

import random

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

You can also use .replace as

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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