手动对 Dataframe 中列中的字符串进行排序

Manually Sorting Strings in Column in Dataframe

我想对数据框中此列中的这些字符串进行排序。我想按收入从低到高或从高到低排序 - 没关系。

最小可重复样本

    K_INCOME    COFFEE_CONSUMER_CATEGORY    HHID_COUNT
1    100,000− 124,999   retained    154022
12   125,000− 149,999   retained    82124
14   15,000− 19,999 retained    26965
10   150,000− 199,999   retained    77617
9    20,000− 29,999 retained    65817
0    200,000− 249,999   retained    36755
7    250,000− 399,999   retained    21755
3    30,000− 39,999 retained    87054
2    40,000− 49,999 retained    110710
8    400,000− 499,999   retained    3493
11   50,000− 59,999 retained    130240
5    60,000− 74,999 retained    168661
13   75,000− 99,999 retained    242603
4   Less than ,000   retained    58331
15  More than 0,000  retained    9694
6   None    retained    130015

我试过收入_df_sorted = income_df.sort_values(by=['K_INCOME']) income_df_sorted 但它 returns 下面。

我试过 Series 有一个替换方法可以做到这一点:

s = income_df['K_INCOME'].replace({'None':0, 'Less than ,000':1, '15,000− 19,999':2})
s.sort_values()

...但出现此类型错误 TypeError: '<' not supported between instances of 'int' and 'str'

关于如何按收入水平排序有什么想法吗?理想情况下,我不必尝试转换为整数,因为它们是一个范围,我需要在较大的数据库中保留为字符串。

(我需要排序,以便我可以绘制收入从低到高,或从高到低。)

更新:需要这样的输出

谢谢! G

正如我在评论中所说,我不确定如何对收入进行排名。对于排序,我刚刚定义了收入超过 50 的人获得 51,而收入低于 50 的人获得 49。其余的我采用了收入上限。所以我使用正则表达式来查找某人的收入是少了还是多了,并设置了一个校正因子。之后拆分并连接字符串以获得字符串形式的收入。在 returning 之前,我将字符串转换为整数并添加校正因子。

def calcIncome(string):

    # value is a correction factor for the income
    value = 0
    if re.search("Less than.*", string) != None:
        value = -1
    elif re.search("More than.*", string) != None:
        value = 1

    #extract highest income
    stringLst = re.split('$|-', string)
    highIncomeLst = stringLst[len(stringLst) - 1].split(',')
    income = ''

    for i in highIncomeLst:
        income += i

    return int(income) + value

sampleDf = pd.DataFrame({'income': ['Less than 3,000', '3000-5000'],
               'B': [21, 32],
            'C': ['a', 'b']})
sampleDf.dropna(subset=['income'], inplace=True)
sampleDf['sorting_income'] = sampleDf.apply(lambda row: calcIncome(row['income']), axis=1)
print(sampleDf.sort_values(by=['sorting_income']))

也许在最终版本中您想要删除新列。你可以使用类似的东西: sampleDF.drop(['sorting_income'], axis=1, inplace=True)

关于你的直方图更新 原则保持不变。编写一个函数,其中 return 是给定收入的一组。像 return 0 表示小于 15 等。而不是像给定的那样使用 df.apply 方法。为了更准确地回答,我需要知道步骤是否始终相同以及有关您所需逻辑的一些信息。我应该把收入低于 50 的人放在哪个组中。在所有较低的组中或最接近 50 或最低的组中。