Python/Pandas - 按标准分组的最佳方式?

标签 python pandas

我试图找到问题的答案,但也许我只是没有将解决方案正确应用于我的情况。这是我创建的用于将数据表中的一些行分组为收入组的方法。我创建了 4 个新数据框,然后在对每个数据框应用索引后将它们连接起来。这是最优的还是有更好的方法?

我应该添加我的目标是使用这些新组和 boxpot“by=”参数创建箱线图。

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)

最佳答案

编辑。 正如 Paul 在评论中提到的,有一个 pd.cut 函数专门用于此类事情,它比我原来的答案优雅得多。

# equal-width bins
df['inc_index'] = pd.cut(df.A, bins=4, labels=[1, 2, 3, 4])

# custom bin edges
df['inc_index'] = pd.cut(df.A, bins=[0, 20000, 30000, 40000, 50000],
                         labels=[1, 2, 3, 4])

请注意,labels 参数是可选的。 pd.cut 生成 ordered categorical Series ,因此您可以按结果列进行排序,而不管标签如何:

df = pd.DataFrame(np.random.randint(1, 20, (10, 2)), columns=list('AB'))
df['inc_index'] = pd.cut(df.A, bins=[0, 7, 13, 15, 20])
print df.sort_values('inc_index')

输出(模随机数)

    A   B inc_index
6   2  16    (0, 7]
7   5   5    (0, 7]
3  12   6   (7, 13]
4  10   8   (7, 13]
5   9  13   (7, 13]
1  15  10  (13, 15]
2  15   7  (13, 15]
8  15  13  (13, 15]
0  18  10  (15, 20]
9  16  12  (15, 20]

原始解决方案。这是对 Alexander's answer 的概括。到可变的铲斗宽度。您可以使用 Series.apply 构建 inc_index 列。例如,

def bucket(v):
    # of course, the thresholds can be arbitrary
    if v < 20000:
        return 1
    if v < 30000:
        return 2
    if v < 40000:
        return 3
    return 4

df['inc_index'] = df.mn_earn_wne_p6.apply(bucket)

或者,如果您确实想避免 def

df['inc_index'] = df.mn_earn_wne_p6.apply(
    lambda v: 1 if v < 20000 else 2 if v < 30000 else 3 if v < 40000 else 4)

请注意,如果您只是想将 mn_earn_wne_p6 的范围分割为相等的桶,那么 Alexander 的方式会更干净、更快。

df['inc_index'] = df.mn_earn_wne_p6 // bucket_width

然后,要生成您想要的结果,您只需按此列排序即可。

df.sort_values('inc_index')

您还可以groupby('inc_index')聚合每个存储桶内的结果。

关于Python/Pandas - 按标准分组的最佳方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36345113/

相关文章:

python - 将 Python 包转换为独立应用程序

python - 根据字典引用的不同列的值对 pandas 列执行算术

python - Pandas.apply 返回随机子字符串

python - 将内存中的 OpenCV 图像写入 BytesIO 或 Tempfile

python - 在 Python 和 Linux 中列出附近/可发现的蓝牙设备,包括已经配对的设备

python - 使用形状因子级别将 pandas.DataFrame 转换为 numpy 张量

python - 利用 Python Input() 对数据集执行 DateShift

python - Pandas 数据框过滤

javascript - 通过CSV文件解析转换为JSON格式文件

python - Dask 工作人员似乎死了,但无法找到工作人员日志来找出原因