替换pandas数据帧的唯一值

时间:2016-06-25 05:33:44

标签: python pandas replace dataframe categories

嗨,我是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']

我想用唯一的整数值替换字符串值。

为简单起见,我可以给你虚拟输入和输出。

输入:

Col1
  A
  A
  B
  B
  B
  C
  C

唯一的df值将如下所示

[ 'A' 'B' 'C' ]
替换列后

应该如下所示

Col1
  1
  1
  2
  2
  2
  3
  3

请告诉我如何通过循环或任何其他方式来实现它,因为我有超过300个唯一值。

1 个答案:

答案 0 :(得分:4)

使用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

Factorizing values

另一个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 - 主要是因为memory usage

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
相关问题