![](/img/trans.png)
[英]Python Pandas - Faster Way to Iterate Through Categories in Data While Removing Outliers (Without For Loop)
[英]A Faster Way of Removing Unused Categories in Pandas?
我在Python中运行一些模型,在类别上使用数据子集。
对于内存使用和预处理,所有分类变量都存储为类别数据类型。
对于我的“分组依据”列中的分类变量的每个级别,我正在运行回归,我需要将所有分类变量重置为该子集中存在的变量。
我目前正在使用.cat.remove_unused_categories()
,这占我总运行时间的近50%。 目前,最糟糕的罪犯是我的分组专栏,其他人没有花费太多时间(因为我猜没有多少级别下降)。
这是一个简化的例子:
import itertools
import pandas as pd
#generate some fake data
alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
keywords = [''.join(i) for i in itertools.product(alphabets, repeat = 2)]
z = pd.DataFrame({'x':keywords})
#convert to category datatype
z.x = z.x.astype('category')
#groupby
z = z.groupby('x')
#loop over groups
for i in z.groups:
x = z.get_group(i)
x.x = x.x.cat.remove_unused_categories()
#run my fancy model here
在我的笔记本电脑上,这需要大约20秒。 对于这个小例子,我们可以转换为str,然后返回到类别以加速,但我的真实数据每组至少有300行。
有可能加快这个循环吗? 我尝试过使用类似时间的xx = xxcat.set_categories(i)
和xxcat.categories = i
,它要求我开始使用相同数量的类别。
您的问题在于您将z.get_group(i)
分配给x
。 x
现在是z
的一部分的副本。 您的代码可以正常使用此更改
for i in z.groups:
x = z.get_group(i).copy() # will no longer be tied to z
x.x = x.x.cat.remove_unused_categories()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.