2024-04-26 18:26:21 发布
网友
假设我有x=["apple","orange","orange","apple","pear"]我想有一个整数的分类表示,例如y=[1,2,2,1,3]。最好的办法是什么?你知道吗
x=["apple","orange","orange","apple","pear"]
y=[1,2,2,1,3]
熊猫:x.astype('category').cat.codes
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]
熊猫:
x.astype('category').cat.codes
可以使用^{} 并使用字段0:
您可以使用:
或:
相关问题 更多 >
编程相关推荐