Add constant list to pandas column

Viewed 588

Assuming I have a df:

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

All I want is to add a new column, c, with a constant list (for example: [7,8,9,10]).

When I try:

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

I get:

ValueError: Length of values does not match length of index

I tried to play also with loc, at, ix - but couldn't figure it out.

An ugly workaround I found is to do something like:

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

But there must be a more elegant way to do it.

2 Answers

Simpler way is:

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

result:

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

UPDATE:

To avoid problem of shallow copy of lists in each row (as @YOBEN_S described), use:

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

Now it is possible to change for example only first element in column c of the first row by calling:

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]

This will add constant list to 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]

This would add column to df using its index

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