将常量列表添加到熊猫列中



假设我有一个df:

df=pd.DataFrame({'a':[1,2,3],'b':[4,5,6]})

我只想添加一个新列c,其中包含一个常量列表(例如:[7,8,9,10](。

当我尝试时:

df['c']=[7,8,9,10]

我得到:

ValueError: Length of values does not match length of index

我也试着玩locatix,但没能玩明白。

我发现一个丑陋的变通方法是做一些类似的事情:

df['c'] = df['b'].apply(lambda x: [7,8,9,10])

但必须有一种更优雅的方式来做到这一点

更简单的方法是:

df['c'] =  [[7,8,9,10]]*len(df)

结果:

a  b              c
0  1  4  [7, 8, 9, 10]
1  2  5  [7, 8, 9, 10]
2  3  6  [7, 8, 9, 10]

更新:

为了避免每行中列表的浅拷贝问题(如@YOBEN_S所述(,请使用:

df['c'] = df.apply(lambda x: [7,8,9,10], axis = 1)

现在可以通过调用:仅更改第一行c列中的第一个元素

df.loc[0,'c'][0]='test'
a  b                 c
0  1  4  [test, 8, 9, 10]
1  2  5     [7, 8, 9, 10]
2  3  6     [7, 8, 9, 10]

这将向df 添加常量列表

#df['c']=pd.Series([[7,8,9,10]]*len(df))
df=df.assign(c=pd.Series([[7,8,9,10]]*len(df)))

a  b              c
0  1  4  [7, 8, 9, 10]
1  2  5  [7, 8, 9, 10]
2  3  6  [7, 8, 9, 10]

这将使用其索引将列添加到df

df['c']=pd.Series([7,8,9,10])
a  b  c
0  1  4  7
1  2  5  8
2  3  6  9

最新更新