Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a column of list to a dataframe python

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?

like image 366
user36729 Avatar asked Jul 19 '26 00:07

user36729


1 Answers

>>> 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]

like image 152
Dennis Golomazov Avatar answered Jul 23 '26 22:07

Dennis Golomazov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!