Pandas如何从聚合中按类别定位?

2024-04-26 05:25:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我将一些数据装箱,然后按仓位分组,用.count计算每个仓位中的条目数,并查询每个仓位的样本数

import pandas as pd
import numpy as np

A = np.random.random(10000)
bins = np.arange(0, max(A), 0.03)

data_bins = pd.cut(A, bins = bins, precision = 100)

df = pd.DataFrame({"A": A,
                   "bin":  data_bins})\
    .sort_values(by = ["bin"])\
    .reset_index(drop = True)\
    .dropna()

print(df.head())

# For example, only take bins with more than 310 entries in each
valid_bins = df.groupby("bin")[["A"]].count().query("A > 310")

print(valid_bins)

所以现在我知道了在我的大数据集中使用valid_bins查找哪些垃圾箱。现在,如何在原始df中仅定位这些箱子


Tags: 数据importdfdatabinascountnp
1条回答
网友
1楼 · 发布于 2024-04-26 05:25:08

我认为您需要^{}用于Series,其大小与原始DataFrame相同,因此可以通过^{}进行过滤:

df1 = df[df.groupby("bin")["A"].transform('count') > 310]

或者将slowier溶液与filtration一起使用:

df1 = df.groupby("bin").filter(lambda x: x["A"].count() > 310)

print(df1.head())
            A           bin
674  0.080059  (0.06, 0.09]
675  0.074179  (0.06, 0.09]
676  0.062529  (0.06, 0.09]
677  0.087312  (0.06, 0.09]
678  0.070065  (0.06, 0.09]

相关问题 更多 >