熊猫重命名索引

a1234

我有以下数据框,在这里我想将索引从重命名summaryid

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
洛兹

您需要删除列名称:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章