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

时间:2017-10-01 20:37:41

标签: python indexing

假设这些是来自具有许多行的DataFrame(df)的4行。

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

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

这有效:

df.index.values[1] ='DE55'
df.index.values[2] ='QVXYZ'
df
       a  b    
AB01   1  5
DE55   2  6
QVXYZ  3  7
JK05   4  8

但我作弊了。我知道标签DE55和GH33在行上 这个非常小的样本的df.iloc [1]和df.iloc [2]。

如果DataFrame有很多行,而且我不知道标签在哪一行上 我想改变,我该怎么做?有没有办法从标签中获取索引整数而不是逐行显式迭代?

2 个答案:

答案 0 :(得分:0)

考虑到这一点:

l = ["March","b"]

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

返回

['Mar', 'b']

怎么样:

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

答案 1 :(得分:0)

您可以使用词典有效地替换索引标签,而无需事先知道标签所在的DataFrame行。诀窍是首先交换行和列。

一般方法是

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.

例:
假设我们有以下DataFrame,并希望更改索引标签A,B和G.

df starts out:
--------------
  col1   col2  col3  col4
A  foo    one     0     0
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
G  foo    one     6    12
H  foo  three     7    14

创建一个包含要更改标签的字典 字典的名称值对将构造为

  

{'要更改的索引标签' :'将其更改为' }

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

下面的代码链将上面的3个步骤连接在一起 更改oldNewRowXref字典中规定的索引标签:

  

df.transpose()。重命名(列= 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