python - 考虑到数据分布,离散化 Pandas 的列

标签 python performance pandas numpy

我有一个 pandas 的数据框,其中一列包含从 0 到 50 的真实数据。它们分布不均匀。

我可以使用以下方式获取发行版:

hist, bins = np.histogram(df["col"])

我想做的是将每个值替换为其所属的垃圾箱编号。

为此,这是有效的:

for i in range(len(df["speed_array"])):
    df["speed_array"].iloc[i] = np.searchsorted(bins, df["speed_array"].iloc[i])

但是,对于超过 400 万行的数据帧,速度相当慢(50 分钟)。我正在寻找一种更有效的方法来实现这一点。你们有更好的主意吗?

最佳答案

只需使用 np.searchsorted在整个底层数组数据上 -

df["speed_array"] = np.searchsorted(bins, df["speed_array"].values)

运行时测试 -

In [140]: # 4 million rows with 100 bins
     ...: df = pd.DataFrame(np.random.randint(0,1000,(4000000,1)))
     ...: df.columns = [['speed_array']]
     ...: bins = np.sort(np.random.choice(1000, size=100, replace=0))
     ...: 

In [141]: def searchsorted_app(df):
     ...:     df["speed_array"] = np.searchsorted(bins, df["speed_array"].values)
     ...:     

In [142]: %timeit searchsorted_app(df)
10 loops, best of 3: 15.3 ms per loop

关于python - 考虑到数据分布,离散化 Pandas 的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44435458/

相关文章:

python-3.x - pandas groupby apply 不会广播到 DataFrame

python - "Never invent such names; only use them as documented."谁?

python - 如何将 Python 列表写入持久存储?

python - 由于未找到模块 'pd.core.dtypes.common',本地 Ubuntu 机器拒绝导入 Pandas

java - Activemq 消息速率

python - 与列表相比,从数据框中提取字符串

python - python语法中 `~`是什么意思

windows - TortoiseSVN 在某些 Windows 配置上非常慢

java - 为什么相加解析的 double 比在 Java 中使用 BigDecimal 慢?

python - 为什么 pandas read_csv 转换器的性能要慢得多并且是非矢量化的?