How do you unpack a list in a df and use addition on that list without making a loop

Viewed 40

I want to add a column to my df from a list and then add or minus numbers from each row of the df for that column.

list_of_num  = [1,2,3,4,5]
a_variable = 4

df["New_num"] = list_of_num + a_variable

desired output

New_num
5
6
7
8
9

I get the error TypeError: unsupported operand type(s) for -: 'list' and 'int'

3 Answers

Try this.

df["New_num"] = [num + a_variable for num in list_of_num]

May be you can create Series out of list_of_num then add a_variable:

df['New_num'] = pd.Series(list_of_num) + a_variable

Or even more efficient (time complexity) seems to be use of numpy array:

import numpy as np

df['New_num'] = np.array(list_of_num) + a_variable

Use List comprehension. This will be quite performant:

In [2858]: l = [ i + a_variable for i in list_of_num]

In [2859]: l
Out[2859]: [5, 6, 7, 8, 9]

df['New_num'] = l
Related