Reputation: 69
I have a pandas dataframe which I would like to add a new column to. The new column values will be determined by an existing column in the dataframe which contains bools. The code below is my C++ logic applied in python but I would like a more 'pythonic' way to do this. 'isfixed'
contains the bools and the new column will be 'color code'
for i in range(data_2015['isfixed'].count()):
if data_2015['isfixed'][i] == True:
data_2015['color code'][i] = 'Blue'
else:
data_2015['color code'][i] = 'Green'
Thanks in advance for the help!
Upvotes: 2
Views: 2801
Reputation: 26
For a pure Pandas solution:
df = pd.DataFrame({'isfixed': [True, False, True]})
df['color_code'] = ["Blue" if value==True else "Green" for value in df['isfixed']]
Upvotes: 0
Reputation:
You can use numpy.where
:
import numpy as np
data_2015['color_code'] = np.where(data_2015['isfixed'], 'Blue', 'Green')
A demo:
df = pd.DataFrame({'isfixed': [True, False, True]})
df
Out:
isfixed
0 True
1 False
2 True
df['color_code'] = np.where(df['isfixed'], 'Blue', 'Green')
df
Out:
isfixed color_code
0 True Blue
1 False Green
2 True Blue
Upvotes: 2