Skip to content Skip to sidebar Skip to footer

Randomly Assign Values To Subset Of Rows In Pandas Dataframe

I am using Python 2.7.11 with Anaconda. I understand how to set the value of a subset of rows of a Pandas DataFrame like Modifying a subset of rows in a pandas dataframe, but I nee

Solution 1:

You must determine the size of group 2

g2 = df['group'] == 2
df.loc[g2, 'value'] = np.random.randint(5, size=g2.sum())
print(df)

   group  value
0      1    NaN
1      1    NaN
2      1    NaN
3      2    3.0
4      2    4.0
5      2    2.0

Post a Comment for "Randomly Assign Values To Subset Of Rows In Pandas Dataframe"