从 value_counts() 更改索引类型

问题描述

我试图在 int 之后将索引类型从 string 更改为 value_counts()

df
['value']
.value_counts()
.sort_index()

输出

40.0      1448
45.0     28558
50.0     83675
55.0     96377
60.0     47351
65.0     13226
70.0      2602
75.0       568
80.0        72
100.0       52
105.0       53
Name: value,dtype: int64

预期输出

40.0      1448
45.0     28558
50.0     83675
55.0     96377
60.0     47351
65.0     13226
70.0      2602
75.0       568
80.0        72
100.0       52
105.0       53
Name: value,dtype: string

解决方法

如果需要转换像 40.0 这样的排序索引值,请使用 rename:

df['value'].value_counts().sort_index().rename(index=str)

如果需要转换计数值,如 1448 使用 Series.astype

df['value'].value_counts().sort_index().astype(str)