Skip to content Skip to sidebar Skip to footer

How To Rename Entries In Pandas Dataframe?

I have a dataframe like this df= a b 54 12 54 16 18 3 3 33 I want to rename the entries starting from 0 and return something like this: df1= a b 0 1 0 2 3 4 4 5

Solution 1:

IIUC, you can get the list of unique values in your dataframe with:

In [1]: pd.Series(df.values.flatten()).unique()
Out[1]: array([54, 12, 16, 18,  3, 33])

Let's make it into a series (you'll see why):

In [2]: series = pd.Series(pd.Series(df.values.flatten()).unique())
In [3]: series
Out[3]:
    005411221631843533

Now all you need to do is replace the original values with the index of the above series.


For a given value, e.g. 16, here is how you do it:

In[4]: series[series==16].index[0]Out[4]: 
2

Now you can apply this to the entire dataframe with a lambda function. The method applymap will apply the lambda function to each element separately:

In[5]: df.applymap(lambda x: series[series==x].index[0])
Out[5]:
   ab001102234345

Post a Comment for "How To Rename Entries In Pandas Dataframe?"