Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

pandas - Changing index type from a value_counts()

I am trying to change the index type from int to string after a value_counts()

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

output:

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

expected output:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If need convert sorted index values like 40.0 use rename:

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

If need convert count values like 1448 use Series.astype:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...