Reputation: 7245
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
Upvotes: 1
Views: 784
Reputation: 16241
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]:
0
0 54
1 12
2 16
3 18
4 3
5 33
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]:
a b
0 0 1
1 0 2
2 3 4
3 4 5
Upvotes: 1