Skip to content Skip to sidebar Skip to footer

Add Constant List To Pandas Column

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,1

Solution 1:

Simpler way is:

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

result:

ab              c
014[7, 8, 9, 10]125[7, 8, 9, 10]236[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'
ab                 c
014[test, 8, 9, 10]125[7, 8, 9, 10]236[7, 8, 9, 10]

Solution 2:

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
014  [7, 8, 9, 10]
125  [7, 8, 9, 10]
236  [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

Post a Comment for "Add Constant List To Pandas Column"