Python 自定义聚合 - 需要更高效的解决方案

Python custom aggregates - need a more efficient solution

我是 Python 的新手,我正在使用一个感兴趣的数据集来帮助我学习,特别是试图更好地理解 pandas 和 numpy。

我的数据框有超过一百万行,我正在尝试创建一个自定义存储桶,以便找到更多有趣的见解。我的数据集如下所示:

我的数据表:

Price    Postal_area    Purchase_Month
123000   SE22           2018_01
240000   GU22           2017_02
.
.
.

我想将数据分组到 < 100000、200k - 300k、300k - 500k、500k+ 的价格范围内,然后我想按价格范围、月份和邮政区域进行分组。我对创建自定义价格桶感到困惑。

我尝试做的是创建一个自定义函数:

def price_range(Price):
    if (Price <= 100000):
        return ("Low Value")
    elif (100000 < Price < 200000):
        return ("Medium Value")
    elif (200001 < Price < 500000):
        return ("Medium High")
    elif (Price > 500001):
        return ("High")
    else:
        return ("Undefined")


然后我在我的数据集中创建一个新列,如下所示:

for val in (my_table.Price):
    my_table["price_range"] = (price_range(val))

我应该能够从中创建一个聚合,但它是一个极其缓慢的过程 - 已经 运行 超过 30 分钟,一百万行左右,但仍然 运行!

我曾尝试使用 numpy 和 pandas(pivot table、groupby、lambdas)创建自定义数据桶,但无法弄清楚如何合并自定义数据桶逻辑.

我查看了其他一些答案,例如下面的答案,但没有涵盖我的特定自定义需求:

非常感谢任何帮助!

使用 apply 函数将自定义函数 price_range 应用到 my_table

my_table['price_range']=my_table['Price'].apply(price_range)

如果您想要范围相等的 bin:

my_table['price_range']=pd.cut(my_table['Price'], bins = 4, labels = ['Low Value', 'Medium Value', 'Medium High', 'High'])

您可以尝试使用 pd.cut 来削减范围内的值并指定要分配的标签 df

    Price
0   12300
1   24000
2   232455
3   343434343


pd.cut(df.Price,[0,100000,200000,500000,np.inf],labels=['Low_value','Medium Value','High','Undefined'])

输出:

0    Medium Value
1            High
2            High
3       Undefined
Name: Price, dtype: category
Categories (4, object): [Low_value < Medium Value < High < Undefined]