Fill the value in all rows of data based on the value

So I have a dataframe as follows

   name, car
    foo, bmw
    bar, audi
    baz, tesla
    foobaz, bmw

I now have another dictionary, for example

car_type = {'bmw': 'gas', 'audi': 'hybrid', 'tesla': 'electric'}

Now I want to add a new column to the dataframe as shown below.

   name, car, type
    foo, bmw, gas
    bar, audi, hybric
    baz, tesla, electric
    foobaz, bmw, gas

How to do it in pandas?

+4
source share
2 answers
df['easy_peasy'] = df.car.map(car_type)
+4
source

if your dict key does not contain all the car names and you want to fill in the missing car name with a specific type by default, then this will help.

df['type'] = df.car.map(lambda x: car_type[x] if x in car_type else 'water')

More 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
+4
source

Source: https://habr.com/ru/post/1675662/


All Articles