pythonPandas\n用整数编码唯一

2024-04-26 18:26:21 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有x=["apple","orange","orange","apple","pear"]我想有一个整数的分类表示,例如y=[1,2,2,1,3]。最好的办法是什么?你知道吗


Tags: apple分类整数pearorange办法
3条回答

熊猫:x.astype('category').cat.codes

可以使用^{}并使用字段0:

In [465]: pd.factorize(x)
Out[465]: (array([0, 1, 1, 0, 2]), array(['apple', 'orange', 'pear'], dtype=object))

In [466]: pd.factorize(x)[0] + 1
Out[466]: array([1, 2, 2, 1, 3])

您可以使用:

import pandas as pd

x=["apple","orange","orange","apple","pear"]
s = pd.Series(x)

print s

0     apple
1    orange
2    orange
3     apple
4      pear

print pd.Categorical(s).codes

[0 1 1 0 2]

或:

import pandas as pd

x=["apple","orange","orange","apple","pear"]

print pd.Categorical(x).codes

#[0 1 1 0 2]

相关问题 更多 >