Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill value in all rows of dataframe based on value

Tags:

python

pandas

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?

like image 932
frazman Avatar asked Jan 05 '23 02:01

frazman


2 Answers

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
like image 53
John Avatar answered Jan 11 '23 09:01

John


df['easy_peasy'] = df.car.map(car_type)
like image 25
ℕʘʘḆḽḘ Avatar answered Jan 11 '23 10:01

ℕʘʘḆḽḘ