pandas - 在大型数据集上进行多组计数活动的最有效方法
问题描述
我正在尝试查找属性(列)值的子集(任何长度),它们在给定数据集中是唯一的。据我所知,找到这些的最有效方法是计算多个(许多)groupby 活动,计算 pandas 中相应的组大小。由于循环可能变得非常大,那么在同一数据集上加速那些按任务分组的最有效方法是什么?
groups = [["a","b"],["a","b","c"],["c","a"]] # this can be really large
df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), columns=['a', 'b', 'c'])
for g in groups:
r = df.groupby(g, sort=False).size().reset_index().rename(columns={0:'count'})
if r.loc[r['count']==1]['count'].count() > 0:
# do something
解决方案
根据数据集的大小,最好使用 dask-cudf 库而不是 cudf 库。请注意,对于使用 dask-cudf 的小型数据集,上述过程将花费更多时间。上述代码片段的 dask-cudf 实现:
import cudf
import dask_cudf
groups = [["a","b"],["a","b","c"],["c","a"]] # this can be really large
df = cudf.DataFrame({'a':[1, 2, 1], 'b': [4, 5, 4], 'c':[7, 8, 9]})
ddf = dask_cudf.from_cudf(df, npartitions=2) # value for npartitons can be changed to see speed up
for g in groups:
r = ddf.groupby(g, sort=False).size().reset_index().rename(columns={0:'count'})
num_non_repeated_values = r.loc[r['count']==1]['count'].count().compute()
if num_non_repeated_values > 0:
print(num_non_repeated_values)
如果你能提供更多关于你想用获得的信息做什么的信息,它真的会帮助我找到更有效的算法来实现上述r
代码num_non_repeated_values
。
推荐阅读
- ruby-on-rails - 为什么简单表单在 Rails 中不显示验证错误消息?
- android - 为 Android 中的 WebView 内的按钮设置 onClick 侦听器
- javascript - 如何让一个函数在运行之前等待另一个函数的完成
- css - Bootstrap 类留下了一些我需要删除的空格
- vue.js - Vuetify `v-file-input` 在选择文件后立即提交文件,而不是在点击提交后
- python - 创建一个 pdf 文件,在其中写入并使用 PyMuPDF 返回其字节流
- javascript - 制表器在添加/更新行后不会重新排序数据
- javascript - JavaScript 如何在 DIV 中打印标签?
- laravel - 在 laravel 中全局搭建 vue 的问题
- pandas - Jupyter notebook 500 错误和 Dataframe 问题