如何替换pandas数据帧中的少量索引标签?

2024-10-16 22:24:22 发布

您现在位置:Python中文网/ 问答频道 /正文

假设这是一个数据帧(df)中的4行,其中有许多行。在

       a  b    
AB01   1  5
DE44   2  6
GH33   3  7
JK05   4  8

我的目标是更改索引标签。
具体来说,我想把DE44改成DE55,把GH33改成QVXYZ。在

这是有效的:

^{pr2}$

但我作弊了。我知道DE55和GH33标签在行上
测向仪[1] 以及测向仪[2] 这个非常小的样本。在

如果数据帧有很多行,但我不知道标签在哪一行
我想改变,我该怎么做?有没有一种方法可以在不逐行显式迭代的情况下从标签中获取索引整数?在


Tags: 数据方法目标df标签作弊行上样本
2条回答

您可以使用字典来高效地替换索引标签,而无需事先知道标签在数据帧的哪一行。诀窍是首先交换行和列。在

一般做法是

1. use df.transpose() to swap the index and column heading axes
2. use df.rename() to change the row index labels (now column headings!)
3. use df.transpose() to revert the axes to where they were.

示例:
假设我们有下面的数据帧,并希望更改索引标签A、B和G

^{pr2}$

用要更改的标签创建词典。
字典的名称-值对的结构如下

{ 'index label to change' : 'what to change it to' }

oldNewRowXref = {'A':'was row A',
                 'B':'was row B', 
                 'G':'was G'}

以下代码行将上述3个步骤与
按照oldNewRowXref字典中的规定更改索引标签:

df.transpose().rename(columns=oldNewRowXref).transpose()

df index labels changed:
            
          xxx1   col2 col3 lastCol
was row A  foo    one    0       0
was row B  bar    one    1       2
C          foo    two    2       4
D          bar  three    3       6
E          foo    two    4       8
F          bar    two    5      10
was G      foo    one    6      12
H          foo  three    7      14

考虑到这一点:

l = ["March","b"]

[i if i != "March" else "Mar" for i in l]

退货

^{pr2}$

怎么样:

df.index = [i if i != "March" else "Mar" for i in df.index]

相关问题 更多 >