我有一个大数据框(几百万行)。
我希望能够对其进行 groupby 操作,但只是按行的任意连续(最好是大小相等)子集进行分组,而不是使用各个行的任何特定属性来决定它们进入哪个组。
用例:我想通过 IPython 中的并行映射将函数应用于每一行。哪些行进入哪个后端引擎并不重要,因为该函数一次基于一行计算结果。 (至少在概念上是这样;实际上它是矢量化的。)
我想出了这样的东西:
# Generate a number from 0-9 for each row, indicating which tenth of the DF it belongs to
max_idx = dataframe.index.max()
tenths = ((10 * dataframe.index) / (1 + max_idx)).astype(np.uint32)
# Use this value to perform a groupby, yielding 10 consecutive chunks
groups = [g[1] for g in dataframe.groupby(tenths)]
# Process chunks in parallel
results = dview.map_sync(my_function, groups)
但这看起来很冗长,并且不能保证大小相同的块。特别是当索引稀疏或非整数或其他情况时。
有更好的方法建议吗?
Thanks!
使用 numpy 的数组分割():
import numpy as np
import pandas as pd
data = pd.DataFrame(np.random.rand(10, 3))
for chunk in np.array_split(data, 5):
assert len(chunk) == len(data) / 5, "This assert may fail for the last chunk if data lenght isn't divisible by 5"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)