I am trying to assign 0 to random cells in a one dimensional pandas.DataFrame. The below code is the best way I could think of doing this, however I believe there may be a neater approach to this problem.

import numpy as np
import pandas as pd
from random import randint

df = pd.DataFrame(np.random.randint(20, size=(10, 1)), columns=list('A'))
col_size = len(df.columns)
row_size = len(df.index)
df[df.columns[randint(0, col_size-1)]][randint(0, row_size-1)] = 0

Could someone please review and suggest if this is a good approach or there are better ways to do this?


Right now, you are only setting a single cell to zero. If this is what you want, then your solution works well. However, if you want to randomly set cells to be 0, then the solutions below might be better. For an arbitrary dimensional df:

# Create Random Mask
rand_zero_one_mask = np.random.randint(2, size=df.shape)
# Fill df with 0 where mask is 0
df = df.where(rand_zero_one_mask==0, 0)

Note: df.where is not to be confused with np.where


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.