gpt4 book ai didi

python - 在 Pandas DataFrame 列中进行整数编码后将 dtype 保留为类别

转载 作者:行者123 更新时间:2023-11-28 18:03:50 25 4
gpt4 key购买 nike

我有一个从 csv 中读取的 Pandas DataFrame,它有一些带有字符串值的列,但实际上是 object 类型。因为它们是分类的,所以我将它们转换为 category,然后转换为整数表示,然后我拟合了一个随机森林回归器。

for col in df_raw.select_dtypes(include='object'):
df_raw[col] = df_raw[col].astype('category')
df_raw[col] = df_raw[col].cat.codes #not 'category' type anymore.

问题是如果我这样做,dtype 会立即转换为 int 而我会丢失我需要的 cat 信息之后。

例如,在循环的第一行之后,我可以运行 df_raw[col].cat,我会按预期获得索引类别。但是一旦执行第二行,dtype 列变为 int8,我将得到错误:

Can only use .cat accessor with a 'category' dtype`

这在某种程度上非常合理,因为它的 dtype 是 int8

是否可以在同一个 DataFrame 中保留类别编码信息,同时使用整数编码来适应回归器?怎么办?

最佳答案

<强>1。简单的想法

为什么不在回归器拟合中使用派生列,例如:

df_raw[col + '_calculated'] = df_raw[col].cat.codes

通过这种方式,您同时拥有:一个不会更改此功能的分类列 col 和一个根据需要使用 int 进行进一步处理的“计算”列?

<强>2。更聪明的方法

另一种方法是在将数据帧传递给 fit 方法之前包装数据帧,这样回归器可以访问 .cat.codes 而不是直接访问分类值:

def access_wrapper(dframe, col):
yield from dframe[col].cat.codes

fit(..., access_wrapper(df, col))

通过这种方式,您根本不会影响数据帧,也不会以调用 dframe[col].cat.codes< 为代价从 df[col] 复制值 每次访问该值(应该相当快)。

关于python - 在 Pandas DataFrame 列中进行整数编码后将 dtype 保留为类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54716954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com