替换 pandas 数据框的唯一值
Replace unique values of pandas data-frame
嗨,我是 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
个唯一值。
使用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
solution, but slowier in huge :
_,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
- mainly because less 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
嗨,我是 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
个唯一值。
使用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
solution, but slowier in huge
_,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
- mainly because less 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