如何使用索引编号在Pandas中重命名列标题

3

I have the following data frame

import pandas as pd
df = pd.DataFrame({ 'gene':["foo",
                            "lal",
                            "qux",
                            "woz"], 'cell1':[5,9,1,7], 'cell2':[12,90,13,87]})
df = df[["gene","cell1","cell2"]]
df

看起来是这样的:

  gene  cell1  cell2
0  foo      5     12
1  lal      9     90
2  qux      1     13
3  woz      7     87

我想要做的是更改第1列和第3列的列名。 结果如下:
    X  cell1   Y
  foo      5  12
  lal      9  90
  qux      1  13
  woz      7  87

如何使用索引编号 02 来完成此操作。

我可以做到这一点。

df.columns = ["X","cell1","Y"]

但它不使用列索引。
2个回答

5
从列中制作列表,修改列表,然后将列表重新分配给columns属性:
>>> cols = list(df.columns)
>>> cols[0] = 'X'
>>> cols[2] = 'Y'
>>> df.columns = cols

或者,可以只用一行代码:

>>> df.rename(columns={'cell1': 'X', 'gene': 'Y'}, inplace=True)

2
df.columns._data[0] = 'X'

df.columns._data[2] = 'Y'

>>> df
     X  cell1   Y
0  foo      5  12
1  lal      9  90
2  qux      1  13
3  woz      7  87

总的来说,当有疑问时,请查看类的 __dict__ 变量:

>>> df.columns.__dict__
{'freq': None, '_cache': {'dtype': dtype('O'), 'is_all_dates': False, 'is_unique': True, 'inferred_t
ype': 'string', '_engine': <pandas.index.ObjectEngine object at 0x000000000882DC48>}, '_data': array
(['gene', 'cell1', 'cell2'], dtype=object), '_id': <object object at 0x00000000028F4720>, 'name': No
ne}

3
一个以下划线开头的名字通常意味着“嘿,假装我不存在!” 它不是公共API的一部分,因此,除非已经记录为可以使用,否则它可能在未来消失并破坏依赖它的代码。有时访问这样的“私有”属性可能会很有用,但有一种通过公共API完成这个操作的方式,所以我认为这不是正当情况。 - jme

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接