Reputation: 9692
In my files one column containing different grades( columns name='Grades).
eg: 91 50K,92 60K,DIESEL,ADBlU etc..
For all these grades I need to categorize them in few grades;
eg: 91 50K= Petrol
In my python, how can i do this? Note that i can pass the whole column to the function. but function has to rewrite each row's value with the correct one;
def checkgrades(data):
df['Grades']=???
???
As per below answers I try;
df_dips=map_dips_grades(df_dips)
df_sales = df_sales.merge(df_dips, left_on=['Site Name', 'Date','GradeNo'],
right_on=['Site', 'Dip Time', 'Product'], how='left').fillna(0)
def map_dips_grades(data):
d1 = {'Diesel': ['DIESEL', 'DIESEL 1'],
'Unleaded': ['91','91 UNLEADED'],
'PULP':['95','95 ULP'],
'PULP98':['98','98 20K'],
'Vortex Diesel':['DIESEL ULT R'],
'Adblue':['ADBLU','ADO']}
d = {k: oldk for oldk, oldv in d1.items() for k in oldv}
data['Product'].map(d)
return data
But I get;
ValueError: You are trying to merge on int64 and object columns. If you wish to proceed you should use pd.concat
Upvotes: 2
Views: 207
Reputation: 820
You can try using a dictionary along with the map() function. Something like this:
dict = {'91 50K': 'Petrol', .........}
df['Grades'] = df['Grades'].map(dict)
Upvotes: 2
Reputation: 863166
You can create dictionary of all possible values in Grades
and then Series.map
:
#test all possible unique values
print (df['Grades'].unique())
d = {'91 50K':'Petrol','92 60K':'Petrol','DIESEL':'Diesel',...}
df['Grades'] = df['Grades'].map(d)
Another possible dictionary for less typing is dict of lists:
d1 = {'Petrol':['91 50K','92 60K'],
'Diesel':['DIESEL']}
#swap key values in dict
#http://stackoverflow.com/a/31674731/2901002
d = {k: oldk for oldk, oldv in d1.items() for k in oldv}
print (d)
{'91 50K': 'Petrol', '92 60K': 'Petrol', 'DIESEL': 'Diesel'}
df['Grades'] = df['Grades'].map(d)
Upvotes: 1