我有以下数据框,我想在其中将索引重命名summary为id:
summary student count
0 error 6
1 yes 1
2 no 1
3 other 9
Run Code Online (Sandbox Code Playgroud)
我试过:
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
Run Code Online (Sandbox Code Playgroud)
我也试过:df.index.rename('foo', inplace = True)它给出:
summary student count
foo
0 error 6
1 yes 1
2 no 1
3 other 9
Run Code Online (Sandbox Code Playgroud)
我也试过:df.rename_axis('why', inplace = True)它给出:
summary student count
why
0 error 6
1 yes 1
2 no 1
3 other 9
Run Code Online (Sandbox Code Playgroud)
当我这样做时df.dtypes:
summary
student object
count init64
dtype: object
Run Code Online (Sandbox Code Playgroud)
我想要什么:
id student count
0 error 6
1 yes 1
2 no 1
3 other 9
Run Code Online (Sandbox Code Playgroud)
或者:
student count
0 error 6
1 yes 1
2 no 1
3 other 9
Run Code Online (Sandbox Code Playgroud)
您需要删除列名:
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')
Run Code Online (Sandbox Code Playgroud)
问题是'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
Run Code Online (Sandbox Code Playgroud)
当您然后尝试添加索引名称时,很明显这'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
Run Code Online (Sandbox Code Playgroud)
但是没有歧义:当您有索引名称时,列会升高一级,这样您就可以区分索引名称和列名称。
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
Run Code Online (Sandbox Code Playgroud)
您需要访问索引的属性
df.index.name = 'id'
Run Code Online (Sandbox Code Playgroud)
原来的
student count
summary
0 error 6
1 yes 1
2 no 1
3 other 9
Run Code Online (Sandbox Code Playgroud)
固定 df:
student count
id
0 error 6
1 yes 1
2 no 1
3 other 9
Run Code Online (Sandbox Code Playgroud)
更新:似乎您有列索引的名称。你应该删除它
df.columns.names = ''
| 归档时间: |
|
| 查看次数: |
13360 次 |
| 最近记录: |