Firstly, there is no need to loop through each and every index, just use pandas built in boolean indexing. First line here, we gather all of the values in Column2
that are the same as variable1
and set the same row in Column3
to be variable2
df.ix[df.Column2==variable1, 'Column3'] = variable2
df.ix[df.Column2==variable3, 'Column3'] = variable4
A simple example would be
import pandas as pd
df = pd.DataFrame({'Animal':['dog', 'fish', 'fish', 'dog']})
print(df)
Animal
0 dog
1 fish
2 fish
3 dog
df.ix[df.Animal=='dog', 'Colour'] = 'brown'
df.ix[df.Animal=='fish', 'Colour'] = 'silver'
print(df)
Animal Colour
0 dog brown
1 fish silver
2 fish silver
3 dog brown
The above method can be build on very easily using multiple conditions like &
and |
to boolean index.
df = pd.DataFrame({'Animal':['dog', 'fish', 'fish', 'dog'], 'Age': [1, 3, 2, 10]})
print(df)
Age Animal
0 1 dog
1 3 fish
2 2 fish
3 10 dog
df.ix[(df.Animal=='dog') & (df.Age > 8), 'Colour'] = 'grey' # old dogs go grey
df.ix[(df.Animal=='dog') & (df.Age <= 8), 'Colour'] = 'brown'
df.ix[df.Animal=='fish', 'Colour'] = 'silver'
print(df)
Age Animal Colour
0 1 dog brown
1 3 fish silver
2 2 fish silver
3 10 dog grey