Reputation: 1317
I have a dataframe where the names of the fruits are in integer format. However, I would like to replace them with actual string names.
fruit_names = {'1' : 'Grapes', '2' : 'Oranges', '3' : 'Apples'}
order_inventory = pd.DataFrame({'Year': [1997,1998,1999],'Fruit': [1,2,1], 'Qty': [12,15,12]})
print order_inventory
Fruit Qty Year
0 1 12 1997
1 2 15 1998
2 1 12 1999
What is the easiest method to perform this in 1 operation vs doing it individually for each fruit type ? [This is an example, so I could have more items in my name_list]
Upvotes: 0
Views: 90
Reputation: 15953
You'll need to have the dictionary as int
since Fruit
is int
as well. Then simply use map
.
fruit_names = {1 : 'Grapes', 2 : 'Oranges', 3 : 'Apples'}
order_inventory = pd.DataFrame({'Year': [1997,1998,1999],'Fruit': [1,2,1], 'Qty': [12,15,12]})
order_inventory['Fruit'].map(fruit_names)
Out[81]:
0 Grapes
1 Oranges
2 Grapes
Name: Fruit, dtype: object
If your dictionary is actually in string and you have many items, you can do the following to convert to int:
fruit_names = {int(k):str(v) for k,v in fruit_names.items()}
fruit_names
Out[101]: {1: 'Grapes', 2: 'Oranges', 3: 'Apples'}
Upvotes: 1
Reputation: 2677
import pandas as pd
fruit_names = {1 : 'Grapes', 2 : 'Oranges', 3 : 'Apples'}
order_inventory = pd.DataFrame({'Year': [1997,1998,1999],'Fruit': [1,2,1], 'Qty': [12,15,12]})
convert_to_string = lambda x: fruit_names[x]
order_inventory['Fruit'] = order_inventory['Fruit'].apply(convert_to_string)
print order_inventory
>>> order_inventory
Fruit Qty Year
0 Grapes 12 1997
1 Oranges 15 1998
2 Grapes 12 1999
Upvotes: 0