pandas 重命名索引 [英] Pandas rename index

查看:70
本文介绍了 pandas 重命名索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据框,我想在其中将索引从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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆