0

I imported a dataframe from excel using

data = pd.read_csv('transaction.csv')

and have a dataframe that looks like this

         Date      Time  Transaction           Item
0  2016-10-30  09:58:11            1          water
1  2016-10-30  10:05:34            2   french fries
2  2016-10-30  10:05:34            2       Icecream
3  2016-10-30  10:07:57            3      chocolate
4  2016-10-30  10:07:57            3        Cookies

I have created a dictionary to assign each item to either a food or drink category like this:

Food = ('french fries', 'Icecream', 'chocolate', 'Cookies')
Drink = ('water')
Category = {Food : "Food", Drink : "Drink"}

I want to assign the categories to another column but it comes out as NaN. I used this code:

data['Classification'] = data['Item'].map(Category)


         Date      Time  Transaction           Item Food or Drink
0  2016-10-30  09:58:11            1          water           NaN
1  2016-10-30  10:05:34            2   french fries           NaN
2  2016-10-30  10:05:34            2       icecream           NaN
3  2016-10-30  10:07:57            3      chocolate           NaN
4  2016-10-30  10:07:57            3        cookies           NaN

What would be the best way to fix this?

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252

1 Answers1

1

Create dictionary for each category by dict.fromkeys and merge them together:

Food = ('french fries', 'Icecream', 'chocolate', 'Cookies')
Drink = ('water',)

Category = {**dict.fromkeys(Food, "Food"), **dict.fromkeys(Drink, "Drink")}
print (Category)
{'french fries': 'Food', 'Icecream': 'Food', 
 'chocolate': 'Food', 'Cookies': 'Food', 'water': 'Drink'}

data['Classification'] = data['Item'].map(Category)
print (data)
         Date      Time  Transaction          Item Classification
0  2016-10-30  09:58:11            1         water          Drink
1  2016-10-30  10:05:34            2  french fries           Food
2  2016-10-30  10:05:34            2      Icecream           Food
3  2016-10-30  10:07:57            3     chocolate           Food
4  2016-10-30  10:07:57            3       Cookies           Food
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252