jeudi 1 février 2018

Add a Rand to each row using Pandas' Assign and a Lambda Function

How do I pass a random number to a lambda function, so that I can be used by the pandas assign to add a different random number to each row.

My original attempt,

df = pd.DataFrame({'cat': [1]*10 + [0]*10,
                   'value': [3]*5 + [2]*5 + [2]*2 + [3]*8})

df.assign(cat=lambda df: df.cat + np.random.rand(1)).head(3)

Out[1]:
     cat        value
0   1.962857    3
1   1.962857    3
2   1.962857    3

We see here that the the random number 0.962857 has been added to all rows. But I would like a different rand for each row. How can I do this?




Aucun commentaire:

Enregistrer un commentaire