0

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?

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

6 Comments

The problem with your code is that random.choice only pick one letter for all replaced rows
@AlbertoCastillo are you sure ? it is supposed to take random selections
Yep... I ran your code and all 1 numbers has been replaced by only one letter, random, but just one letter, f.i. 1 by 'X' or 1 by 'Y'. And I think it makes sense due to replace and where takes all rows = 1 and replace with any letter, all in one step, it's not like iteration... but your answer has been marked as good so I suppose it works for @Thelonius. Cheers!
@Alberto Castillo Indeed, the issue you described is true. I did not check it properly earlier. The above code replaces each '1' with the same random element from the list
I have updated the answer, let me know if it works?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.