Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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]
like image 633
00__00__00 Avatar asked Nov 02 '18 09:11

00__00__00


People also ask

How do I apply a function to each row in a DataFrame?

Use apply() function when you wanted to update every row in pandas DataFrame by calling a custom function. In order to apply a function to every row, you should use axis=1 param to apply(). By applying a function to each row, we can create a new column by using the values from the row, updating the row e.t.c.

How do you select a rows of a DataFrame based on a list of values?

To select the rows from a Pandas DataFrame based on input values, we can use the isin() method.


1 Answers

Just to complete my earlier answer with df.assign, borrowed list comprehension from @jezrael

>>> df
   A  B
0  1  4
1  2  5
2  3  6

>>> df.assign(C =  [mylist for i in df.index])
   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]

OR, to add permanently to the DataFrame

df = df.assign(C =  [mylist for i in df.index])

Another way of doing it with df.insert

as we are specifying the order of the column, hence can use insert here by inserting at index 2 (so should be third col in dataframe)

>>> df.insert(2, 'C', '[10, 20, 30, 40, 50]') # directly assigning the list
>>> 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]
like image 183
Karn Kumar Avatar answered Oct 12 '22 08:10

Karn Kumar