Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

python - Pandas rename index

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

I have tried: newdf = df.reset_index().rename(columns={df.index.name:'foo'}) which gives:

summary  index    student  count    
0        0        error   6
1        1        yes     1
2        2        no      1
3        3        other   9

I have also tried: df.index.rename('foo', inplace = True) which gives:

 summary     student  count
 foo        
 0           error    6
 1           yes      1
 2           no       1
 3           other    9

I have also tried: df.rename_axis('why', inplace = True) which gives:

 summary     student  count
 why        
 0           error    6
 1           yes      1
 2           no       1
 3           other    9

When I do df.dtypes:

summary
student object
count   init64
dtype:  object

What I would like:

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to remove the column name:

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')

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...