gpt4 book ai didi

python - Numpy/pandas 优化 : bins counting

转载 作者:太空宇宙 更新时间:2023-11-03 14:10:51 24 4
gpt4 key购买 nike

我想“装箱”一个numpy.arraypandas.Series x通过数数N begin 之间的值和 end .结果存储在 pandas.DataFrame 中:

import numpy as np
import pandas as pd
bins = pd.DataFrame({'from': np.arange(0, 1, 0.01), 'to': np.arange(0, 1, 0.01) + 0.1})
x = np.random.rand(1000000)
bins['N'] = bins.apply(lambda r: ((x >= r['from']) & (x < r['to'])).sum(), axis=1)

当我剖析代码时,整个脚本中最慢的部分(包含更多内容)如果是最后一行,尤其是 lambda:15% 的时间花在了那个 lambda 上!

我有一种感觉,而不是使用 lambda ,我必须以矢量化的方式实现,但我不知道如何实现。

我正在使用 Python 3.5、numpy 1.11 和 pandas 0.18.1


编辑:附加信息 + 使用 intervaltree 进行测试

事实上,分箱是迭代使用的:分箱是从一些数据开始的,并且可能会随着其他数据集而更新。

如建议的那样,我已经尝试使用 intervaltree,但它在性能方面甚至变得最差。从第二次迭代开始,我收到了一个用户警告,因为 numexpr 不支持 boold dtype 上的 '+',因此它切换到纯 python 模式。

最佳答案

间隔具有规则大小这一事实可能会被滥用以大大加快代码速度。因此,设置参数后,您可以使用 NumPy's bincount procedure , 像这样 -

# First off, filter out elements that are outside the min,max limits.
# Then subtract min_val from the filtered elements so that they all start from 0
# Then, scale them w.r.t width and floor them, thus converting them into IDs
IDs = ((x[(x >= min_val) & (x<=max_val)]-min_val)/width).astype(int)

# Finally count those IDs, which is the desired output as new column
bins['N'] = np.bincount(IDs)

因此,对于发布的示例,我们将参数设置为:

min_val = 0
max_val = 1
width = 0.1

sample 运行-

In [156]: # Params
...: min_val = 4
...: max_val = 8
...: width = 0.4
...:
...: # Create inputs
...: bins = pd.DataFrame({'from': np.arange(4, 8, 0.4), 'to':
...: np.arange(4, 8, 0.4) + 0.4})
...: x = 10*np.random.rand(1000)
...:

In [157]: bins['N'] = bins.apply(lambda r: ((x >= r['from']) & \
...: (x < r['to'])).sum(), axis=1)

In [158]: bins
Out[158]:
from to N
0 4.0 4.4 42
1 4.4 4.8 40
2 4.8 5.2 36
3 5.2 5.6 43
4 5.6 6.0 45
5 6.0 6.4 29
6 6.4 6.8 40
7 6.8 7.2 46
8 7.2 7.6 41
9 7.6 8.0 45

In [159]: IDs = ((x[(x >= min_val) & (x<=max_val)]-min_val)/width).astype(int)

In [160]: np.bincount(IDs)
Out[160]: array([42, 40, 36, 43, 45, 29, 40, 46, 41, 45])

关于python - Numpy/pandas 优化 : bins counting,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38182101/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com