Python 熊猫重命名索引
我有以下数据框,其中我想将索引从Python 熊猫重命名索引,python,pandas,Python,Pandas,我有以下数据框,其中我想将索引从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
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
summary student count
foo
0 error 6
1 yes 1
2 no 1
3 other 9
summary student count
why
0 error 6
1 yes 1
2 no 1
3 other 9
我也尝试过:df.index.rename('foo',inplace=True)
它给出:
summary index student count
0 0 error 6
1 1 yes 1
2 2 no 1
3 3 other 9
summary student count
foo
0 error 6
1 yes 1
2 no 1
3 other 9
summary student count
why
0 error 6
1 yes 1
2 no 1
3 other 9
我也尝试过:df.rename_axis('why',inplace=True)
,它给出:
summary index student count
0 0 error 6
1 1 yes 1
2 2 no 1
3 3 other 9
summary student count
foo
0 error 6
1 yes 1
2 no 1
3 other 9
summary student count
why
0 error 6
1 yes 1
2 no 1
3 other 9
当我执行df.d类型时:
summary
student object
count init64
dtype: object
我想要的是:
id student count
0 error 6
1 yes 1
2 no 1
3 other 9
或:
您需要访问索引的属性
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 = df.drop('summary', axis=1)
df['id'] = np.arange(df.shape[0])
df.set_index('id', inplace=True)
然后可以得到所需的结果。您需要删除列名:
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\u 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
这里回答:
df.index.name='id'
在摘要
之外添加id
,而不是重命名摘要
。不知道发生了什么。