- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有一个很大的 csv,每行有两个字符串,格式如下:
g,k
a,h
c,i
j,e
d,i
i,h
b,b
d,d
i,a
d,h
我阅读了前两列并将字符串重新编码为整数,如下所示:
import pandas as pd
df = pd.read_csv("test.csv", usecols=[0,1], prefix="ID_", header=None)
from sklearn.preprocessing import LabelEncoder
# Initialize the LabelEncoder.
le = LabelEncoder()
le.fit(df.values.flat)
# Convert to digits.
df = df.apply(le.transform)
此代码来自https://stackoverflow.com/a/39419342/2179021 .
该代码工作得很好,但当 df 很大时速度很慢。我为每个步骤计时,结果令我惊讶。
pd.read_csv
大约需要 40 秒。 le.fit(df.values.flat)
大约需要 30 秒df = df.apply(le.transform)
大约需要 250 秒。有什么方法可以加快这最后一步吗?感觉应该是最快的一步了!
在具有 4GB RAM 的计算机上重新编码步骤的更多计时
maxymoo 下面的答案很快,但没有给出正确答案。以问题顶部的示例 csv 为例,它将其转换为:
0 1
0 4 6
1 0 4
2 2 5
3 6 3
4 3 5
5 5 4
6 1 1
7 3 2
8 5 0
9 3 4
请注意,“d”在第一列中映射到 3,而在第二列中映射到 2。
我尝试了 https://stackoverflow.com/a/39356398/2179021 中的解决方案并获得以下信息。
df = pd.DataFrame({'ID_0':np.random.randint(0,1000,1000000), 'ID_1':np.random.randint(0,1000,1000000)}).astype(str)
df.info()
memory usage: 7.6MB
%timeit x = (df.stack().astype('category').cat.rename_categories(np.arange(len(df.stack().unique()))).unstack())
1 loops, best of 3: 1.7 s per loop
然后我将数据帧大小增加了 10 倍。
df = pd.DataFrame({'ID_0':np.random.randint(0,1000,10000000), 'ID_1':np.random.randint(0,1000,10000000)}).astype(str)
df.info()
memory usage: 76.3+ MB
%timeit x = (df.stack().astype('category').cat.rename_categories(np.arange(len(df.stack().unique()))).unstack())
MemoryError Traceback (most recent call last)
此方法似乎使用了太多 RAM 来尝试转换它崩溃的这个相对较小的数据帧。
我还使用具有 1000 万行的较大数据集对 LabelEncoder 进行计时。它运行时没有崩溃,但仅拟合线就花了 50 秒。 df.apply(le.transform) 步骤耗时约 80 秒。
我怎样才能:
最佳答案
看起来使用 pandas category
数据类型会快得多;在内部,它使用哈希表,而 LabelEncoder 使用排序搜索:
In [87]: df = pd.DataFrame({'ID_0':np.random.randint(0,1000,1000000),
'ID_1':np.random.randint(0,1000,1000000)}).astype(str)
In [88]: le.fit(df.values.flat)
%time x = df.apply(le.transform)
CPU times: user 6.28 s, sys: 48.9 ms, total: 6.33 s
Wall time: 6.37 s
In [89]: %time x = df.apply(lambda x: x.astype('category').cat.codes)
CPU times: user 301 ms, sys: 28.6 ms, total: 330 ms
Wall time: 331 ms
编辑:这是一个您可以使用的自定义转换器类(您可能不会在官方 scikit-learn 版本中看到它,因为维护者不希望将 pandas 作为依赖)
import pandas as pd
from pandas.core.nanops import unique1d
from sklearn.base import BaseEstimator, TransformerMixin
class PandasLabelEncoder(BaseEstimator, TransformerMixin):
def fit(self, y):
self.classes_ = unique1d(y)
return self
def transform(self, y):
s = pd.Series(y).astype('category', categories=self.classes_)
return s.cat.codes
关于python - 如何加速 LabelEncoder 将分类变量重新编码为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39475187/
我使用 LabelEncoder() 将分类数据转换为数值数据。我有一个数据集,如下所示: ['x','s','n','t','p','f','c','n','k','e','e','s','s','
您可以在下面找到我在互联网上找到的用于构建简单神经网络的代码。一切正常。我对 y 标签进行了编码,这些是我得到的预测: 2 0 1 2 1 2 2 0 2 1 0 0 0 1 1 1 1 1 1 1
LabelEncoder 不会“记住”参数。当我用它拟合和转换数据然后询问参数时,我得到的只是{}。这使得不可能在新数据上重新使用编码器。 例子: from sklearn.preprocessing
摘要:Sklearn 的 LabelEncoder 将不同的值编码为相同的值。 encoder.fit(data) 和 data_encoded =encoder.transform(data) 可以
我正在做一个预测项目(为了好玩),基本上我从 nltk 中提取了男性和女性的名字,将名字标记为“男性”或“女性”,然后获取每个名字的最后一个字母,最后使用不同的机器学习算法根据最后一个字母训练和预测性
我编写了这个函数来使用 LabelEncoder 转换分类特征 #convert columns to dummies with LabelEncoder cols = ['ToolType', 'T
嘿, 我的数据集中的“城市”列中有不同的城市名称。我很想使用 LabelEncoder() 对其进行编码。然而,我得到了非常令人沮丧的负值结果 df['city_enc'] = LabelEncode
嘿, 我的数据集中的“城市”列中有不同的城市名称。我很想使用 LabelEncoder() 对其进行编码。然而,我得到了非常令人沮丧的负值结果 df['city_enc'] = LabelEncode
我遇到有关 LabelEncoder 的问题。我将其应用到数据集,如下所示: data_set1 = data_set.apply(LabelEncoder().fit_transform) ...并
我正在尝试建立一个推理管道。它由两部分组成。使用前几年的一些表格订单元数据进行每月 ML 模型训练,并使用当天的新订单进行每日推理预测。我想在我的模型中包含几个字符串分类列,我使用 labelenco
Closed. This question is off-topic。它当前不接受答案。
Image of ull error 我正在尝试在对象类型的所有列上运行LabelEncoder。这是我编写的代码,但它引发了此错误: TypeError: '<' not supported bet
尝试执行以下代码时出现以下错误。 class LabelOneHotEncoder(): def __init__(self): self.ohe = OneHotEncode
我正在编写一个脚本,该脚本使用“局部异常值因子”算法进行“新颖性检测”。在这种情况下,我们需要在进行预测之前“拟合”“干净/训练”数据框。为了使算法正常工作,我们需要对数据帧中的值进行编码,例如将“v
我在数据帧上应用了 LabelEncoder(),它返回以下内容: order/new_cart 有不同的标签编码数字,如 70、64、71 等 这是标签不一致,还是我哪里做错了什么? 最佳答案 La
我有一个很大的 csv,每行有两个字符串,格式如下: g,k a,h c,i j,e d,i i,h b,b d,d i,a d,h 我阅读了前两列并将字符串重新编码为整数,如下所示: import
如果 sklearn.LabelEncoder已在训练集上拟合,如果在测试集上使用时遇到新值,它可能会中断。 对此我能想出的唯一解决方案是将测试集中的所有新内容(即不属于任何现有类)映射到 "" ,然
我想使用 sklearn.preprocessing.LabelEncoder 对元组列表进行标签编码, 如: [(4,5), (6, 7), (1, 1), (6, 7), ... ] 这样每个元组
我正在尝试将分类字符串列转换为几个虚拟变量二进制列,但出现值错误。 代码如下: import sys, os import numpy as np import matplotlib.pyplot a
如果我有一个数据框,请说 df,如果 df["levels"] = pd.Series(["low", "low", "med", "low", "med", "high"]) 有没有办法将其更改为:
我是一名优秀的程序员,十分优秀!