1

I have a dataframe with 182 rows. I want to add a column to it full of 0's except for twelve 1's distributed random in the df. Is it possible? Thanks

3 Answers 3

1
df['x']=0
df.loc[df.sample(12).index.tolist(), 'x'] =  1
Sign up to request clarification or add additional context in comments.

1 Comment

This is probably the best answer as it makes great use of native methods.
0

You can use random.shuffle for this

# create members
contents = [1 for _ in range(12)] + [0 for _ in range(182 - 12)]
# shuffle contents in-place
random.shuffle(contents)
# add to df
df["colname"] = contents

Comments

0

You can use random.choice along with list comprehension:

import random
df['NEW_COL'] = [0]*182
df['NEW_COL'][[random.choice(range(182)) for x in range(12)]] = 1

Comments

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.