问题描述
我想在我的数据框中的这一列中对这些字符串进行排序。我想按收入从低到高或从高到低排序 - 无所谓。
最小可重复样本
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 $15,000 retained 58331
15 More than $500,000 retained 9694
6 None retained 130015
我尝试了收入_df_sorted = income_df.sort_values(by=['K_INCOME'])
收入_df_sorted 但它返回以下内容。
s = income_df['K_INCOME'].replace({'None':0,'Less than $15,000':1,'15,999':2})
s.sort_values()
...但是得到了这个类型错误 TypeError: '
关于如何按收入水平排序的任何想法?理想情况下,我不必尝试转换为整数,因为它们是一个范围,我需要在更大的数据库中保留为字符串。
(我需要排序,以便我可以将收入从低到高或从高到低绘制。)
更新:像这样所需的输出
谢谢! G
解决方法
正如我在评论中所说,我不确定如何对收入进行排名。对于排序,我刚刚定义了收入超过 50 的人的收入为 51,而收入低于 50 的人的收入为 49。其余的我取了收入上限。所以我使用正则表达式来查找某人的收入是少还是多,并设置了一个修正系数。之后拆分并连接字符串以获取字符串形式的收入。在返回之前,我将字符串转换为整数并添加校正因子。
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)
关于直方图更新 原理不变。编写一个函数,返回给定收入的组。像小于 15 的返回 0 等等。并且比使用 df.apply 像给定的方法。为了更准确地回答,我需要知道这些步骤是否始终相同以及有关您所需逻辑的一些信息。我把收入低于 50 的人放在哪个组中。在所有较低的组中,或者最接近 50 或最低。