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]
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.
To select the rows from a Pandas DataFrame based on input values, we can use the isin() method.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With