【问题标题】:Pandas rename index熊猫重命名索引
【发布时间】:2019-07-28 08:30:59
【问题描述】:

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


【解决方案1】:

您需要删除列名:

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

【讨论】:

    【解决方案2】:

    您需要访问索引的属性

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

    【讨论】:

    • df.index.name = 'id'summary 之外添加id,而不是重命名summary。不知道发生了什么。
    【解决方案3】:

    首先你可以删除列:

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

    那么就可以得到想要的结果了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-21
      • 2020-09-04
      • 2021-12-07
      • 2023-01-05
      • 2020-03-24
      • 2019-11-01
      • 2019-08-06
      • 1970-01-01
      相关资源
      最近更新 更多