So I have a dataframe as follows
   name, car
    foo, bmw
    bar, audi
    baz, tesla
    foobaz, bmw
now I have another dictionary like
car_type = {'bmw': 'gas', 'audi': 'hybrid', 'tesla': 'electric'}
Now, i want to add a new column to dataframe like following
   name, car, type
    foo, bmw, gas
    bar, audi, hybric
    baz, tesla, electric
    foobaz, bmw, gas
How do i do this in pandas?
if your dict key doesn't contain all car names and you want to fill missing car name with some default type, then this will help.
df['type'] = df.car.map(lambda x: car_type[x] if x in car_type else 'water')
In details
df['name'] = ['foo', 'bar', 'baz', 'faz', 'zaz']
df['car'] = ['bmw', 'audi', 'tesla', 'bmw', 'skoda']
car_type = {'bmw': 'gas', 'audi': 'hybrid', 'tesla': 'electric'}
df['type1'] = df.car.map(car_type)
df['type2'] = df.car.map(lambda x: car_type[x] if x in car_type else 'water')
print(df)
  name    car     type1      type2
0  foo    bmw       gas       gas
1  bar   audi    hybrid    hybrid
2  baz  tesla  electric  electric
3  faz    bmw       gas       gas
4  zaz  skoda       NaN     water
                        df['easy_peasy'] = df.car.map(car_type)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With