how to assign an entire list to each row of a pandas dataframe

  • A+
Category:Languages

I have a dataframe and a list

df = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6]}) mylist= [10,20,30,40,50] 

I would like to have a list as element in each row of a dataframe. If I do like here,

df['C'] = mylist 

Pandas is trying to broadcast one value per row, so I get an error Length of values does not match length of index.

   A  B   C 0  1  4  [10,20,40,50] 1  2  5  [10,20,40,50] 2  3  6  [10,20,40,50] 

 


First I think working with lists in pandas is not good idea.

But it is possible by list comprehension:

df['C'] = [mylist for i in df.index] #another solution #df['C'] = pd.Series([mylist] * len(df))  print (df)     A  B                     C 0  1  4  [10, 20, 30, 40, 50] 1  2  5  [10, 20, 30, 40, 50] 2  3  6  [10, 20, 30, 40, 50] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: