dimanche 27 septembre 2020

if statement to create new column pandas for string variable

With this dataframe, I would like to create another column that is based on the values of the first column.

data = {'item_name':  ['apple', 'banana', 'cherries', 'duck','chicken','pork']}
df = pd.DataFrame (data, columns = ['item_name'])
Expected df:
item_name  item_type
apple      fruit
banana     fruit
cherries   fruit
duck       meat
beef       meat
pork       meat

Code that I tried:

def item_type(item_name):
   if df['item_name'] is in ['apple','banana','cherries']:
       df['item_type']=='fruit'
   else:
       df['item_type']=='meat'

df = df.apply(item_type)

Aucun commentaire:

Enregistrer un commentaire