2

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!

1
  • 1
    I would say this approach is perfectly pythonic but not very pandonic! Commented Dec 9, 2016 at 20:31

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks @ayhan. I like this, just one line. The pythonic way rules!
You are welcome. Just a note: this can also be done by df['color_code'] = ['Blue' if row else 'Green' for row in df['isfixed']] but built-in numpy/pandas functions are generally much faster than iterating over a Series/array.
Right, I have been warned about iterating over series with respect to speed. My understanding is that it is fastest to apply functions over the entire series rather than iterate through each element, right?
Exactly. Here's a more detailed explanation since you mentioned C: (data types and ufuncs)
0

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']]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.