How to rename entries in pandas dataframe?

谁说胖子不能爱 提交于 2019-12-11 10:46:34

问题


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

回答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]:
    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


来源:https://stackoverflow.com/questions/36651443/how-to-rename-entries-in-pandas-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!