简体   繁体   中英

How to change the integer values of a column to a string from a mapping in pandas?

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]

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'}
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM