转换pandas datafram中的分类数据

2024-09-28 20:40:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含此类型数据的数据帧(列太多):

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怎么会这么聪明?


Tags: 数据name类型dataframeobject整数col2col3
3条回答

如果你只担心你做了一个额外的专栏,然后删除它,只要不使用一个新的专栏在第一时间。

dataframe = pd.DataFrame({'col1':[1,2,3,4,5], 'col2':list('abcab'),  'col3':list('ababb')})
dataframe.col3 = pd.Categorical.from_array(dataframe.col3).codes

你完了。现在由于Categorical.from_array已被弃用,请直接使用Categorical

dataframe.col3 = pd.Categorical(dataframe.col3).codes

如果还需要从索引到标签的映射,还有更好的方法

dataframe.col3, mapping_index = pd.Series(dataframe.col3).factorize()

在下面检查

print(dataframe)
print(mapping_index.get_loc("c"))

这对我有效:

pandas.factorize( ['B', 'C', 'D', 'B'] )[0]

输出:

[0, 1, 2, 0]

首先,要将分类列转换为其数字代码,您可以使用:dataframe['c'].cat.codes.
此外,还可以使用select_dtypes自动选择数据帧中具有特定数据类型的所有列。这样,您可以对多个自动选择的列应用上述操作。

首先制作一个示例数据帧:

In [75]: df = pd.DataFrame({'col1':[1,2,3,4,5], 'col2':list('abcab'),  'col3':list('ababb')})

In [76]: df['col2'] = df['col2'].astype('category')

In [77]: df['col3'] = df['col3'].astype('category')

In [78]: df.dtypes
Out[78]:
col1       int64
col2    category
col3    category
dtype: object

然后使用select_dtypes选择列,然后对每个列应用.cat.codes,可以得到以下结果:

In [80]: cat_columns = df.select_dtypes(['category']).columns

In [81]: cat_columns
Out[81]: Index([u'col2', u'col3'], dtype='object')

In [83]: df[cat_columns] = df[cat_columns].apply(lambda x: x.cat.codes)

In [84]: df
Out[84]:
   col1  col2  col3
0     1     0     0
1     2     1     1
2     3     2     0
3     4     0     1
4     5     1     1

相关问题 更多 >