我有一个包含此类型数据的数据帧(列太多):
col1 int64
col2 int64
col3 category
col4 category
col5 category
列如下:
Name: col3, dtype: category
Categories (8, object): [B, C, E, G, H, N, S, W]
我要将列中的所有值转换为整数,如下所示:
[1, 2, 3, 4, 5, 6, 7, 8]
我在一篇专栏文章中这样解释:
dataframe['c'] = pandas.Categorical.from_array(dataframe.col3).codes
现在我的数据框中有两列-旧的“col3”和新的“c”,需要删除旧列。
那是不好的做法。这是可行的,但在我的数据框中有许多列,我不想手动执行。
这条Python怎么会这么聪明?
如果你只担心你做了一个额外的专栏,然后删除它,只要不使用一个新的专栏在第一时间。
你完了。现在由于
Categorical.from_array
已被弃用,请直接使用Categorical
如果还需要从索引到标签的映射,还有更好的方法
在下面检查
这对我有效:
输出:
首先,要将分类列转换为其数字代码,您可以使用:
dataframe['c'].cat.codes
.此外,还可以使用
select_dtypes
自动选择数据帧中具有特定数据类型的所有列。这样,您可以对多个自动选择的列应用上述操作。首先制作一个示例数据帧:
然后使用
select_dtypes
选择列,然后对每个列应用.cat.codes
,可以得到以下结果:相关问题 更多 >
编程相关推荐