Reputation: 2012
I have a dataframe that looks something like that:
In [2]: df
Out[3]:
A B C D
0 45 88 44 92
1 62 34 2 86
2 85 65 11 31
3 74 43 42 56
My code contains some conditions, and if one of them get fulfilled I want to turn all the values in all the columns to random floats between 0 and 1. I want to keep the shape and the column names the same, so I hope there is an easy way to do this, something like:
In [4]: df2 = df.apply(value_randomization(0,1))
In [5]: df2
Out[6]:
A B C D
0 0.76 0.88 0.44 0.92
1 0.62 0.34 0.2 0.86
2 0.85 0.65 0.11 0.31
3 0.74 0.43 0.42 0.56
Is there such a simple solution to it? If not, what would you recommend me? tnx
Upvotes: 0
Views: 144
Reputation: 2012
Combining the answers by BENY and rhug123 this is the most satisfying solution I have encountered so far:
df2 = pd.DataFrame(data=np.random.random(df.shape), columns=df.columns, index=df.index)
Upvotes: 0
Reputation: 323326
Try with
df[:] = np.random.random(df.shape)
df
Out[283]:
A B C D
0 0.151300 0.196162 0.200368 0.775231
1 0.844184 0.611911 0.055625 0.015523
2 0.687728 0.693773 0.364394 0.357987
3 0.887951 0.882617 0.175575 0.318022
Upvotes: 4
Reputation: 8768
Try this:
df2 = pd.DataFrame(np.random.random(size=(len(df.index),len(df.columns))),columns= df.columns).round(2)
Upvotes: 1