在python中对值进行排序

问题描述 投票:0回答:1

我正在使用python(jupyter notebook)进行一些分析。我想通过函数sort_values()在我的熊猫数据框中对我的值进行排序。首先看起来它工作正常,但它只用于排序2个字符的数字(见图)。对于> 99的国家/地区,我该如何正确排序值?

enter image description here

python pandas sorting
1个回答
2
投票

有问题值是strings,所以按字典顺序排序。

所以首先需要转换为数字:

df4 = df4.astype(int)

样品:

df4 = pd.Series(['102','11','10','10', '119', '14'])
print (df4)
0    102
1     11
2     10
3     10
4    119
5     14
dtype: object

print (df4.sort_values())
2     10
3     10
0    102
1     11
4    119
5     14
dtype: object

df4 = df4.astype(int)
print (df4.sort_values())
2     10
3     10
1     11
5     14
0    102
4    119
dtype: int32
© www.soinside.com 2019 - 2024. All rights reserved.