我试图找到我的问题的答案,但也许我只是没有正确地运用我的解决方案。在我的数据表中,我把我的收入分组。我创建了4个新的数据帧,然后在对每个帧应用索引后将它们连接起来。这是最优的还是有更好的方法来做事情?在
我应该添加我的目标是使用这些新的组和boxpot“by=”参数创建一个boxplot。在
df_nonull1 = df_nonull[(df_nonull['mn_earn_wne_p6'] < 20000)]
df_nonull2 = df_nonull[(df_nonull['mn_earn_wne_p6'] >= 20000) & (df_nonull['mn_earn_wne_p6'] < 30000)]
df_nonull3 = df_nonull[(df_nonull['mn_earn_wne_p6'] >= 30000) & (df_nonull['mn_earn_wne_p6'] < 40000)]
df_nonull4 = df_nonull[(df_nonull['mn_earn_wne_p6'] >= 40000)]
df_nonull1['inc_index'] = 1
df_nonull2['inc_index'] = 2
df_nonull3['inc_index'] = 3
df_nonull4['inc_index'] = 4
frames = [df_nonull1,df_nonull2,df_nonull3,df_nonull4]
results = pd.concat(frames)
编辑。正如保罗在评论中提到的,有一个
pd.cut
函数,它比我最初的答案优雅得多。在请注意,} ,因此您可以根据结果列进行排序,而不考虑标签:
^{pr2}$labels
参数是可选的。pd.cut
生成一个ordered categorical ^{输出(模随机数)
原始解。这是对Alexander's answer变桶宽的推广。您可以使用
Series.apply
构建inc_index
列。例如或者,如果你真的想避免
def
请注意,如果您只想将
mn_earn_wne_p6
的范围细分为相等的桶,那么Alexander的方法更干净、更快。在然后,为了得到您想要的结果,您可以按此列进行排序。在
您还可以
groupby('inc_index')
在每个bucket中聚合结果。在如果所有值都在10k和50k之间,则可以使用整数除法(//)分配索引:
您不需要分解数据帧并将它们串联起来,您需要找到一种从
mn_earn_wne_p6
字段创建inc_index
的方法。在相关问题 更多 >
编程相关推荐