Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map string values in a Pandas Dataframe with integers

In Pandas DataFrame how to map strings in one column with integers. I have around 500 strings in the DataFrame and need to replace them with integers starting with '1'.

Sample DataFrame.

                                    Request  count
547             GET /online/WebResource.axd  37506
424              GET /online/2/2/22001.aspx  13315
699          POST /online/2/6/1/261001.aspx  13236
546          GET /online/ScriptResource.axd  12255
492               GET /online/2/6/Home.aspx  10462
660             POST /online/2/2/22001.aspx   9803

I have taken all the Requests in to a list.

requestlist = df.Request.unique()

No idea of how to map these Requests with 1-500. Similar question. python pandas replacing strings in dataframe with numbers

like image 978
Nilani Algiriyage Avatar asked Mar 12 '14 09:03

Nilani Algiriyage


1 Answers

So what you could do is construct a temporary dataframe and merge this back to your existing dataframe:

temp_df = pd.DataFrame({'Request': df.Request.unique(), 'Request_id':range(len(df.Request.unique()))})

Now merge this back to your original dataframe

df = df.merge(temp_df, on='Request', how='left')
like image 84
EdChum Avatar answered Oct 14 '22 07:10

EdChum