替换熊猫数据框的唯一值

JT2*_*T28 7 python replace categories dataframe pandas

嗨,我是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']
Run Code Online (Sandbox Code Playgroud)

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

为简单起见,我可以为您提供虚拟输入和输出。

输入:

Col1
  A
  A
  B
  B
  B
  C
  C
Run Code Online (Sandbox Code Playgroud)

唯一的df值如下

[ 'A' 'B' 'C' ]
Run Code Online (Sandbox Code Playgroud)

更换色谱柱后应如下所示

Col1
  1
  1
  2
  2
  2
  3
  3
Run Code Online (Sandbox Code Playgroud)

请给我建议使用循环或其他任何方式的方法,因为我拥有的不仅是300唯一值。

jez*_*ael 5

用途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
Run Code Online (Sandbox Code Playgroud)

值分解

另一个numpy.unique解决方案,但在庞大的数据帧中速度较慢:

_,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
Run Code Online (Sandbox Code Playgroud)

最后,您可以将值转换为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
Run Code Online (Sandbox Code Playgroud)