Reputation: 575
I have a data frame in pandas as below:
Type Rand Arrival
0 0.3 4
2 0.64 3
1 0.98 12
Now, I want to add a new column to it that is list in each row:
Type Rand Arrival Park
0 0.3 4 [5,10,15,20]
2 0.64 3 [4,9,14,19]
1 0.98 12 [6,11,16,21]
I want to do that based on the 'Rand' column by comparing it to some values using the following commands:
df.loc[ (df.Rand <= 0.4) , 'Park' ] = [5,10,15,20]
df.loc[ (df.Rand > 0.4) & (df.Rand <= 0.8) , 'Park' ] = [4,9,14,19]
df.loc[ (df.Rand > 0.8) , 'Park' ] = [6,11,16,21]
But I am getting the following error:
Must have equal len keys and value when setting with an iterable.
Could you please tell me hot to overcome this issue?
Upvotes: 3
Views: 428
Reputation: 17339
>>> df.loc[df.Rand <= 0.4, 'Park'] = pd.Series([[5, 10, 15, 20]], index=df.index)
>>> df.loc[(df.Rand > 0.4) & (df.Rand <= 0.8), 'Park'] = pd.Series([[4,9,14,19]], index=df.index)
>>> df.loc[(df.Rand > 0.8), 'Park'] = pd.Series([[6,11,16,21]], index=df.index)
>>> df
Type Rand Arrival Park
0 0 0.30 4 [5, 10, 15, 20]
1 2 0.64 3 [4, 9, 14, 19]
2 1 0.98 12 [6, 11, 16, 21]
Inspired by [1]
Upvotes: 2
Reputation: 1135
df.loc[ (df.Rand <= 0.4) , 'Park' ] = lambda:[5,10,15,20]
df.loc[ (df.Rand > 0.4) & (df.Rand <= 0.8) , 'Park' ] = lambda:[4,9,14,19]
df.loc[ (df.Rand > 0.8) , 'Park' ] = lambda:[6,11,16,21]
df.Park = df.Park.apply(lambda x: x())
Upvotes: 1