熊猫重命名索引

问题描述 投票:1回答:3

我有以下数据框,我想将索引从summary重命名为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

要么:

    student  count 
0   error    6
1   yes      1
2   no       1
3   other    9
python pandas
3个回答
2
投票

您需要删除列名称:

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'是你的专栏名称。如果没有索引名称,则列名将直接放在索引上方,这可能会产生误导:

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'确实是列名。

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

但是没有歧义:当你有一个索引名称时,列被提升一个级别,这允许你区分索引名称和列名称。

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

1
投票

您需要访问索引的属性

df.index.name = 'id'

原版的

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

固定df:

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

更新:似乎你有一个列的索引的名称。你应该删除它

df.columns.names = ''


0
投票

首先你可以删除列:

df = df.drop('summary', axis=1)
df['id'] = np.arange(df.shape[0])
df.set_index('id', inplace=True)

然后你就可以得到想要的结果。

© www.soinside.com 2019 - 2024. All rights reserved.