1

I have a dataframe "veh_contract2_df" like this :

FUEL_CODE   FUEL_TYPE 
1           MARGE+PLUS
10          DIESEL

I would like to add a column "hybrid" which should contain "Y" if there is "+" in FUEL_TYPE and "N" if not.

sub_str = "+"
if(veh_contract2_df.loc[(veh_contract2_df['FUEL_TYPE'].find(sub_str)==-1)]):
    veh_contract2_df['HYBRIDE'] = "Y"
    else:
    veh_contract2_df['HYBRIDE'] ="N"

But i got this error : SyntaxError: invalid syntax (at line 71)

Any idea please? thanks

1
  • try searching for np.where. Will get you what you need. Commented Apr 8, 2021 at 15:08

1 Answer 1

6

Use numpy.where:

In [1923]: import numpy as np

In [1924]: df['hybrid'] = np.where(df.FUEL_TYPE.str.contains('+', regex=False), 'Y', 'N')

In [1925]: df
Out[1925]: 
   FUEL_CODE   FUEL_TYPE hybrid
0          1  MARGE+PLUS      Y
1         10      DIESEL      N
Sign up to request clarification or add additional context in comments.

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.