转换pandas数据帧中的分类数据

时间:2015-08-14 13:31:51

标签: python pandas

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

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',需要删除旧列。

这是不好的做法。这是工作,但在我的数据框架中有很多列,我不想手动完成。

这个pythonic怎么这么聪明?

12 个答案:

答案 0 :(得分:127)

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

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

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

答案 1 :(得分:15)

如果你担心的只是你要制作一个额外的专栏并在以后删除它,那么只需在第一时间使用新专栏。

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

你完成了。现在,{@ 1}}已弃用,请直接使用Categorical.from_array

Categorical

如果你还需要从索引到标签的映射,那么对于相同的

,还有更好的方法
dataframe.col3 = pd.Categorical(dataframe.col3).codes

检查以下

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

答案 2 :(得分:13)

这对我有用:

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

输出:

[0, 1, 2, 0]

答案 3 :(得分:3)

要转换数据集数据的列 C 中的分类数据,我们需要执行以下操作:

from sklearn.preprocessing import LabelEncoder 
labelencoder= LabelEncoder() #initializing an object of class LabelEncoder
data['C'] = labelencoder.fit_transform(data['C']) #fitting and transforming the desired categorical column.

答案 4 :(得分:3)

我要做的是,我replace个值。

像这样-

df['col'].replace(to_replace=['category_1', 'category_2', 'category_3'], value=[1, 2, 3], inplace=True)

通过这种方式,如果col列具有分类值,则将它们替换为数值。

答案 5 :(得分:3)

要将 Dataframe 中的所有列转换为数值数据:

df2 = df2.apply(lambda x: pd.factorize(x)[0])

答案 6 :(得分:2)

@ Quickbeam2k1,见下文 -

dataset=pd.read_csv('Data2.csv')
np.set_printoptions(threshold=np.nan)
X = dataset.iloc[:,:].values

使用sklearn enter image description here

from sklearn.preprocessing import LabelEncoder
labelencoder_X=LabelEncoder()
X[:,0] = labelencoder_X.fit_transform(X[:,0])

答案 7 :(得分:1)

这里需要转换多个列。所以,我使用的一种方法是..

for col_name in df.columns:
    if(df[col_name].dtype == 'object'):
        df[col_name]= df[col_name].astype('category')
        df[col_name] = df[col_name].cat.codes

这会将所有字符串/对象类型列转换为分类。然后将代码应用于每种类别。

答案 8 :(得分:0)

对于某些列,如果您不关心顺序,请使用此

df['col1_num'] = df['col1'].apply(lambda x: np.where(df['col1'].unique()==x)[0][0])

如果您在乎订购,请将其指定为列表并使用

df['col1_num'] = df['col1'].apply(lambda x: ['first', 'second', 'third'].index(x))

答案 9 :(得分:0)

将分类变量转换为虚拟变量/指标变量的最简单方法之一是使用pandas提供的get_dummies。 假设我们有sex是分类值(男性和女性)的数据 并且需要将其转换为虚拟/指示器,这是操作方法。

tranning_data = pd.read_csv("../titanic/train.csv")
features = ["Age", "Sex", ] //here sex is catagorical value
X_train = pd.get_dummies(tranning_data[features])
print(X_train)

Age Sex_female Sex_male
20    0          1
33    1          0
40    1          0
22    1          0
54    0          1

答案 10 :(得分:0)

您可以减少代码,如下所示:

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

f['col1'] =f['col1'].astype('category').cat.codes
f['col2'] =f['col2'].astype('category').cat.codes
f['col3'] =f['col3'].astype('category').cat.codes

f

enter image description here

答案 11 :(得分:0)

这里的答案似乎已经过时了。熊猫现在具有factorize()功能,您可以创建以下类别:

df.col.factorize() 

功能签名:

pandas.factorize(values, sort=False, na_sentinel=- 1, size_hint=None)
相关问题