ahmedaao
ahmedaao

Reputation: 397

How to add a column into Pandas with a condition

here is a simple pandas DataFrame :

data={'Name': ['John', 'Dav', 'Ann', 'Mike', 'Dany'],
     'Number': ['2', '3', '2', '4', '2']}

df = pd.DataFrame(data, columns=['Name', 'Number'])
df

I would like to add a third column named "color" where the value is 'red' if Number = 2 and 'Blue' if Number = 3

This dataframe just has 5 rows. In reality It has thousand rows so I can not just add a simple column manually.

Upvotes: 1

Views: 32

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195613

You can use .map:

dct = {2: "Red", 3: "Blue"}

df["color"] = df["Number"].astype(int).map(dct)  # remove .astype(int) if the values are already integer
print(df)

Prints:

   Name Number color
0  John      2   Red
1   Dav      3  Blue
2   Ann      2   Red
3  Mike      4   NaN
4  Dany      2   Red

Upvotes: 2

Related Questions