如何对分类值进行编码

9

你好,我刚接触Python和Pandas。

我使用Pandas提取了一个列的唯一值。

现在,在获取该列的唯一值之后,它们都是字符串。

['Others, Senior Management-Finance, Senior Management-Sales'
  'Consulting, Strategic planning, Senior Management-Finance'
  'Client Servicing, Quality Control - Product/ Process, Strategic       
   planning'
  'Administration/ Facilities, Business Analytics, Client Servicing'
  'Sales & Marketing, Sales/ Business Development/ Account Management,    
  Sales Support']

我可以帮您把字符串值替换为唯一的整数值。
为了简单起见,我可以提供一个虚拟的输入和输出。
输入:
```html

hello

world

hello

```
输出:
```html

1

2

1

```
Col1
  A
  A
  B
  B
  B
  C
  C

唯一的 df 值将会如下所示:
[ 'A' 'B' 'C' ]

替换后,该列应该是这样的。
Col1
  1
  1
  2
  2
  2
  3
  3

请为我提供一种使用循环或其他方式的方法,因为我有超过300个唯一值。


1个回答

8

使用 pd.factorize

df['Col1'] = pd.factorize(df.Col1)[0] + 1
print (df)
   Col1
0     1
1     1
2     2
3     2
4     2
5     3
6     3

因式分解数值

另一个numpy.unique的解决方案,但在巨大的dataframe中速度较慢:

_,idx = np.unique(df['Col1'],return_inverse=True) 
df['Col1'] = idx + 1
print (df)
   Col1
0     1
1     1
2     2
3     2
4     2
5     3
6     3

最后,您可以将值转换为categorical - 主要是因为更少的内存使用

df['Col1'] = pd.factorize(df.Col1)[0]
df['Col1'] = df['Col1'].astype("category")
print (df)
  Col1
0    0
1    0
2    1
3    1
4    1
5    2
6    2

print (df.dtypes)
Col1    category
dtype: object

我想知道是否有一种方法可以对整个数据框进行操作,而不仅仅是对一个列进行操作。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接