如何重命名 pandas 数据框中的条目? [英] How to rename entries in pandas dataframe?

查看:50
本文介绍了如何重命名 pandas 数据框中的条目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数据框

df=
a  b  
54 12
54 16
18 3
3  33

我想重命名从0开始的条目并返回如下内容:

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

推荐答案

IIUC,您可以使用以下方法获取数据框中唯一值的列表:

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.

对于给定值,例如16,这是您的操作方式:

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

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

现在,您可以使用lambda函数将其应用于整个数据框.方法applymap将lambda函数分别应用于每个元素:

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

这篇关于如何重命名 pandas 数据框中的条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆