问题描述
是否有内置函数通过索引重命名熊猫数据框?
Is there a built in function to rename a pandas dataframe by index?
我以为我知道列标题的名称,但是事实证明第二列中有一些十六进制字符.将来,根据接收数据的方式,我可能会在第2列中遇到此问题,因此我无法将那些特定的十六进制字符硬编码到dataframe.rename()调用中.
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.
是否有一个我无法找到的函数被适当地命名为rename_col_by_index()?
Is there a function that would be appropriately named rename_col_by_index() that I have not been able to find?
例如:
>>> 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
推荐答案
您可以简单地使用
df.columns.values[index] = "New name"
或将所有现有名称替换为新名称
or replace all the existing names with new ones by
df.columns = ["col1", "col2"]
这篇关于根据列索引重命名数据框列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!