vendredi 30 août 2019

Python: Populate new df column based on if statement condition

I'm trying something new. I want to populate a new df column based on some conditions affecting another column with values.

I have a data frame with two columns (ID,Retailer). I want to populate the Retailer column based on the ids in the ID column. I know how to do this in SQL, using a CASE statement, but how can I go about it in python?

I've had look at this example but it isn't exactly what I'm looking for.

Python : populate a new column with an if/else statement

import pandas as pd

data = {'ID':['112','5898','32','9985','23','577','17','200','156']}

df = pd.DataFrame(data)

df['Retailer']=''

if df['ID'] in (112,32):
    df['Retailer']='Webmania'
elif df['ID'] in (5898):
    df['Retailer']='DataHub'
elif df['ID'] in (9985):
    df['Retailer']='TorrentJunkie'
elif df['ID'] in (23):
    df['Retailer']='Apptronix'
else: df['Retailer']='Other'


print(df)

The output I'm expecting to see would be something along these lines:

     ID Retailer
0   112 Webmania
1  5898 DataHub
2    32 Webmania
3  9985 TorrentJunkie
4    23 Apptronix
5   577 Other
6    17 Other
7   200 Other
8   156 Other


Aucun commentaire:

Enregistrer un commentaire