pands.qcut 太慢?使用numpy来让速度起飞

对于数据处理,一般来说,处理数独方面,pdDataFame < pd.Series < np.array

最近在使用 pd.qcut 进行数据划分方面的工作,发现速度真是的是慢的难以忍受

import numpy as np
import pandas as pd

首先构造一个 100 x 5000 的,取值范围在 [1, 100] 的DataFrame

df = pd.DataFrame(np.random.randint(1, 100, (100, 5000)))
df.head()

0123456789…499049914992499349944995499649974998499905463214587296791941…5191706376368810249218895577777882647263…2050673359668492560225372872142753398…8453939060334882566132081129633568927584…193985449707942104647665593938147931661…7436672577470282051

5 rows × 5000 columns

首先使用 pd.qcut 来进行划分,因为pd.qcut传入的参数只能是一维的,

因此,对于DataFrame的操作需要使用apply, 并且指定axis=1(因为我们想要的是对每一行进行划分)

然后指定划分组数 q=5,并且指定结果返回【1-5】之间的label

%%time
pd_result = df.apply(pd.qcut, q=5, axis=1, labels=list(range(1, 6))).values
CPU times: user 699 ms, sys: 7.09 ms, total: 707 ms
Wall time: 706 ms

基于上述的执行结果可以看到,只用pd.qcut进行数据划分耗费时间约为706ms,实际处理的数据更加复杂的时候,耗费的时间会更多。

我们看下划分结果:

pd_result
array([[3, 4, 2, ..., 1, 2, 5],
       [5, 5, 3, ..., 3, 2, 4],
       [1, 1, 2, ..., 5, 3, 4],
       ...,
       [2, 3, 4, ..., 3, 5, 5],
       [5, 4, 3, ..., 2, 2, 1],
       [3, 2, 2, ..., 5, 5, 2]], dtype=object)

我们再来看下使用numpy实现pd.qcut功能

至于为啥numpy比pandas快,相信有很多博客已经给了解释,这里就不赘述了

%%time
def np_qcut(arr, q):
    """ 输入的arr是numpy 一维数组"""

    res = np.zeros(arr.size)

    na_mask = np.isnan(arr)
    res[na_mask] = np.nan
    x = arr[~na_mask]

    sorted_x = np.sort(x)
    idx = np.linspace(0, 1, q+1) * (sorted_x.size - 1)
    pos = idx.astype(int)
    fraction = idx % 1
    a = sorted_x[pos]
    b = np.roll(sorted_x, shift=-1)[pos]
    bins = a + (b - a) * fraction

    bins[0] -= 1

    res[~na_mask] = np.digitize(x, bins, right=True)
    return res

np_result = np.apply_along_axis(np_qcut, axis=1, arr=df.values, q=5)
CPU times: user 35.2 ms, sys: 2.61 ms, total: 37.8 ms
Wall time: 36.5 ms

芜湖~

看到使用 np_qcut进行划分耗费的时间约为 36.5ms,比 pd.qcut速度快了将近 20 倍!

我们接下来看下 pd.qcut划分的结果和 np_qcut划分的结果是否一致:

np.alltrue(pd_result == np_result)
True

从上面的对比结果来看,所有的划分结果都是一致的,说明使用numpy实现pd.qcut成功!

ヾ(o´∀`o)ノ

Original: https://blog.csdn.net/qq_36797973/article/details/121433226
Author: 啸啸不说话
Title: pands.qcut 太慢?使用numpy来让速度起飞

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/739337/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球