pandas 重命名索引 [英] Pandas rename index
问题描述
我有以下数据框,我想在其中将索引从summary
重命名为id
:
I have the following dataframe, where I want to rename the index fromsummary
to id
:
summary student count
0 error 6
1 yes 1
2 no 1
3 other 9
我尝试过:
newdf = df.reset_index().rename(columns={df.index.name:'foo'})
给出:
summary index student count
0 0 error 6
1 1 yes 1
2 2 no 1
3 3 other 9
我也尝试过:df.index.rename('foo', inplace = True)
给出:
summary student count
foo
0 error 6
1 yes 1
2 no 1
3 other 9
我也尝试过:df.rename_axis('why', inplace = True)
给出:
summary student count
why
0 error 6
1 yes 1
2 no 1
3 other 9
当我做df.dtypes
时:
summary
student object
count init64
dtype: object
我想要的东西:
id student count
0 error 6
1 yes 1
2 no 1
3 other 9
OR:
student count
0 error 6
1 yes 1
2 no 1
3 other 9
推荐答案
您需要删除列名:
df.rename_axis(None, axis=1).rename_axis('id', axis=0)
##if pd.__version__ == 0.24.0
#df.rename_axis([None], axis=1).rename_axis('id')
问题在于'summary'
是您的列名.如果没有索引名称,则列名称将直接放在索引上方,这可能会引起误解:
The problem is that 'summary'
is your column name. When there is no index name, the column name is placed directly above the index, which can be misleading:
import pandas as pd
df = pd.DataFrame([[1]*2]*4, columns=['A', 'B'])
df.columns.name = 'col_name'
print(df)
#col_name A B
#0 1 1
#1 1 1
#2 1 1
#3 1 1
当您尝试添加索引名称时,很明显'col_name'
确实是列名称.
When you then try to add an index name, it becomes clear that 'col_name'
was really the column name.
df.index.name = 'idx_name'
print(df)
#col_name A B
#idx_name
#0 1 1
#1 1 1
#2 1 1
#3 1 1
但是并没有歧义:当您有索引名称时,列会提升一级,这使您可以区分索引名称和列名称.
There is no ambiguity though: when you have an index name, the columns are raised one level, which allows you to distinguish between an index name and a column name.
df = pd.DataFrame([[1]*2]*4, columns=['A', 'B'])
df.index.name = 'idx_name'
print(df)
# A B
#idx_name
#0 1 1
#1 1 1
#2 1 1
#3 1 1
这篇关于 pandas 重命名索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!