使用排名(Python)对字符串的频率分布进行排序

4

我需要按照预设的等级排序一个字符串变量(教育水平),以下是我写的代码。然而,它仍然使用字母表顺序排序(请查看附加的图片),我不知道出了什么问题。

education_rank = {' Bachelors':12, ' HS-grad':8, ' 11th':6, ' Masters':14, ' 9th':5, ' Some-college':11, ' Assoc-acdm':10, ' Assoc-voc':9, ' 7th-8th':4, ' Doctorate':15, ' Prof-school':13, ' 5th-6th':3, ' 10th':16, ' 1st-4th':2, ' Preschool':1, ' 12th':7}

fd_education = pd.value_counts(adult_data.education)
print(fd_education)
    
fd_education = fd_education.sort_index(level='education_rank')
print(fd_education)

enter image description here

1个回答

2

尝试以下方法 -

  1. education_rank 排序为一个序列以获取索引值
  2. 使用索引值从 value_counts 序列中获取行
  3. 如果有任何缺失值,则 Dropna
#Your predefined rankings
education_rank = {'Bachelors':12, 'HS-grad':8, '11th':6, 'Masters':14, '12th':77}

#Your frequency output from value_counts()
fd_education = pd.Series({'Bachelors':500, 'HS-grad':809, '11th':23, 'Masters':65})

fd_education[pd.Series(education_rank).sort_values().index].dropna()

11th          23
HS-grad      809
Bachelors    500
Masters       65
dtype: int64

解释 -

问题在于您将字典传递给了级别,而不是系列对象的索引名称。级别的目标是帮助处理多索引情况。这让它决定要按哪个索引进行排序。您不能提供要排序的列表/字典作为序列。

如果它无法找到您提供的索引名称,它将只是按字母顺序重新排序。请查看此示例 -

#Your predefined rankings
education_rank = {'Bachelors':12, 'HS-grad':8, '11th':6, 'Masters':14, '12th':77}

#Your frequency output from value_counts()
fd_education = pd.Series({'Bachelors':500, 'HS-grad':809, '11th':23, 'Masters':65})
    
fd_education = fd_education.sort_index(level='hello') #<---- 
print(fd_education)

11th          23
Bachelors    500
HS-grad      809
Masters       65
dtype: int64

请阅读文档以获取更多详细信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接