jeudi 22 août 2019

How to apply IF, else, else if condition in Pandas DataFrame

I have a column in my pandas DataFrame with country names. I want to apply different filters on the column using if-else conditions and have to add a new column on that DataFrame with those conditions.

I have tried this but in this, I have to define countries again and again.

bookings_d2.loc[(bookings_d2.Country== 'Denmark') | (bookings_d2.Country== 'Norway'), 'Country'] = bookings_d2.Country

In R I am currently using if else condition like this, I want to implement this same thing in python.

R Code Example 1 : ifelse(bookings_d2$COUNTRY_NAME %in% c('Denmark','Germany','Norway','Sweden','France','Italy','Spain','Germany','Austria','Netherlands','Croatia','Belgium'), as.character(bookings_d2$COUNTRY_NAME),'Others')

R Code Example 2 : ifelse(bookings_d2$country %in% c('Germany'), ifelse(bookings_d2$BOOKING_BRAND %in% c('BV'),'Germany_BV','Germany_DC'),bookings_d2$country)

I expect: ('Denmark','Germany','Norway', 'Sweden','France', 'Italy', 'Spain','Germany', 'Austria', 'Netherlands','Croatia','Belgium') should remain same and other countries should be tagged as others.

Aucun commentaire:

Enregistrer un commentaire