在Pandas数据框中转换分类数据 [英] Convert categorical data in pandas dataframe

查看:67
本文介绍了在Pandas数据框中转换分类数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,其中包含这种类型的数据(列太多):

I have a dataframe with this type of data (too many columns):

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]

我想像这样将列中的所有值转换为整数:

I want to convert all value in columns to integer like this:

[1, 2, 3, 4, 5, 6, 7, 8]

我通过以下方法解决了这一问题:

I solved this for one column by this:

dataframe['c'] = pandas.Categorical.from_array(dataframe.col3).codes

现在我的数据框中有两列-旧的col3和新的c,需要删除旧的列.

Now I have two columns in my dataframe - old col3 and new c and need to drop old columns.

这是不好的做法.它可以工作,但是在我的数据框中有很多列,我不想手动进行.

That's bad practice. It's work but in my dataframe many columns and I don't want do it manually.

如何巧妙地使用这种Python语言?

How do this pythonic and just cleverly?

推荐答案

首先,要将分类"列转换为其数字代码,可以使用以下方法更轻松地实现:dataframe['c'].cat.codes.
此外,可以使用select_dtypes自动选择数据帧中具有特定dtype的所有列.这样,您可以将以上操作应用于多个自动选择的列.

First, to convert a Categorical column to its numerical codes, you can do this easier with: dataframe['c'].cat.codes.
Further, it is possible to select automatically all columns with a certain dtype in a dataframe using select_dtypes. This way, you can apply above operation on multiple and automatically selected columns.

首先创建一个示例数据框:

First making an example dataframe:

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,您将获得以下结果:

Then by using select_dtypes to select the columns, and then applying .cat.codes on each of these columns, you can get the following result:

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

这篇关于在Pandas数据框中转换分类数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆