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
df['x']=0
df.loc[df.sample(12).index.tolist(), 'x'] = 1
1 Comment
ti7
This is probably the best answer as it makes great use of native methods.
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