pandas 根据列索引重命名 Dataframe 列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41685917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:48:04  来源:igfitidea点击:

Rename Dataframe column based on column index

pythonpandas

提问by aberger

Is there a built in function to rename a pandas dataframe by index?

是否有内置函数可以按索引重命名Pandas数据框?

I thought I knew the name of my column headers, but it turns out the second column has some hexadecimal characters in it. I will likely come across this issue with column 2 in the future based on the way I receive my data, so I cannot hard code those specific hex characters into a dataframe.rename() call.

我以为我知道列标题的名称,但结果发现第二列中有一些十六进制字符。根据我接收数据的方式,我将来可能会在第 2 列中遇到这个问题,因此我无法将这些特定的十六进制字符硬编码到 dataframe.rename() 调用中。

Is there a function that would be appropriately named rename_col_by_index() that I have not been able to find?

是否有一个函数可以适当地命名为 rename_col_by_index() ,但我无法找到?

Ex:

前任:

>>> df = pd.DataFrame({'a':[1,2], 'b':[3,4]})
>>> df.rename_col_by_index(1, 'new_name')
>>> df
   a  new_name
0  1         3
1  2         4

回答by taoufik A

You can simply use

你可以简单地使用

df.columns.values[index] = "New name"

or replace all the existing names with new ones by

或用新名称替换所有现有名称

df.columns = ["col1", "col2"]

回答by MaxU

UPDATE: thanks to @Vincenzzzochi:

更新:感谢@Vincenzzzochi

In [138]: df.rename(columns={df.columns[1]: 'new'})
Out[138]:
   a  new  c
0  1    3  5
1  2    4  6

In [140]: df
Out[140]:
   a  b  c
0  1  3  5
1  2  4  6

or bit more flexible:

或者更灵活一点:

In [141]: mapping = {df.columns[0]:'new0', df.columns[1]: 'new1'}

In [142]: df.rename(columns=mapping)
Out[142]:
   new0  new1  c
0     1     3  5
1     2     4  6