Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a list to existing column of Pandas Data Frame?

Tags:

python

pandas

I apply some functions and generate a new column values to a existing column of Pandas dataframe. However df['col1'] = new_list does not work to assign new list to the column. Is it the wrong way and what is the accurate way to apply such operation ?

like image 720
erogol Avatar asked Nov 04 '13 23:11

erogol


2 Answers

I think this question is looking for something like this.

new_list = [1,2,3]

    col1
0  [1,2,3]
1  [1,2,3]
2  [1,2,3]

And I think I found the answer here:

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

like image 135
codenewbie Avatar answered Oct 11 '22 14:10

codenewbie


It should work if length of the list is equal to the number of rows in the DataFrame

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

If your list is shorter or longer than DataFrame, then you'll receive an error Length of values does not match length of index.

like image 44
Roman Pekar Avatar answered Oct 11 '22 13:10

Roman Pekar