将列列添加到数据帧python

时间:2016-11-02 17:04:33

标签: list pandas dataframe

我在pandas中有一个数据框如下:

    Type      Rand      Arrival
     0         0.3        4
     2         0.64       3
     1         0.98       12

现在,我想在其中添加一个新列,即每行中的列表:

    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]

我想基于' Rand'做到这一点。列使用以下命令将其与某些值进行比较:

   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]

但是我收到以下错误:

  Must have equal len keys and value when setting with an iterable.

请你告诉我热门来解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

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

受[1]

的启发

答案 1 :(得分:1)

mysql_connect
相关问题