I am trying to set the value of a pandas column based on another columns value. The new value should be set by iterating through a list, that has the same length like the unique values of col1
Example:
d = {'col1': [1, 2,2,2,3,3,4], 'col2': [1,1,1,1,1,1,1]}
df = pd.DataFrame(data=d)
items_to_add=[5,2,11,9]
#list has length of unique values in `column1`
Now i want to add for example 5 to column2
if column1
is 1 and 2 to all column2
rows where column1
is 2 ....
So i should get:
col1 col2
1 5
2 2
2 2
2 2
3 11
3 11
4 9
This code throws me an syntax error but i do not know why
items_to_add=[5,2,11,9]
for i in range(len(items_to_add)):
df['col2'][df.col1[i]] = items_to_add[i]
What am I doing wrong? How can i fix it?