【发布时间】:2022-01-15 18:05:54
【问题描述】:
我有一个数据框
- 500 万行。
- 一列
group_id,其唯一元素数为500.000。 - 成千上万的其他列名为
var1、var2等。var1、var2、...中的每一个都只包含 0 和 1。
我想按group_id 分组,然后总结它们。为了获得更好的性能,我使用 dask。但是,这种简单的聚合速度仍然很慢。
The time spent on a dataframe with 10 columns is 6.285385847091675 seconds
The time spent on a dataframe with 100 columns is 64.9060411453247 seconds
The time spent on a dataframe with 200 columns is 150.6109869480133 seconds
The time spent on a dataframe with 300 columns is 235.77087807655334 seconds
我的真实数据集包含多达 30.000 列。我已经阅读了@Divakar 关于使用 numpy 的答案(1 和 2)。但是,前一个线程是关于计数的,而后者是关于对列求和的。
您能否详细说明一些加快这种聚合的方法?
import numpy as np
import pandas as pd
import os, time
from multiprocessing import dummy
import dask.dataframe as dd
core = os.cpu_count()
P = dummy.Pool(processes = core)
n_docs = 500000
n_rows = n_docs * 10
data = {}
def create_col(i):
name = 'var' + str(i)
data[name] = np.random.randint(0, 2, n_rows)
n_cols = 300
P.map(create_col, range(1, n_cols + 1))
df = pd.DataFrame(data, dtype = 'int8')
df.insert(0, 'group_id', np.random.randint(1, n_docs + 1, n_rows))
df = dd.from_pandas(df, npartitions = 3 * core)
start = time.time()
df.groupby('group_id').sum().compute()
end = time.time()
print('The time spent on a dataframe with {} columns is'.format(n_cols), end - start, 'seconds')
【问题讨论】:
-
真正的数据集从哪里来?
-
@JeffUK 它是通过将
pd.get_dummies应用于具有 25 列的原始数据框而生成的。 -
group_id 来自 0 到 499999?
-
@dankal444 范围从 1 到 500.000。
标签: python pandas numpy pandas-groupby