【发布时间】:2016-07-14 23:35:21
【问题描述】:
我想获取数组中唯一行的索引。唯一的行应该有自己的索引(从零开始)。这是一个例子:
import numpy as np
a = np.array([[ 0., 1.],
[ 0., 2.],
[ 0., 3.],
[ 0., 1.],
[ 0., 2.],
[ 0., 3.],
[ 0., 1.],
[ 0., 2.],
[ 0., 3.],
[ 1., 1.],
[ 1., 2.],
[ 1., 3.],
[ 1., 1.],
[ 1., 2.],
[ 1., 3.],
[ 1., 1.],
[ 1., 2.],
[ 1., 3.]])
在上面的数组中有六个唯一的行:
import pandas as pd
b = pd.DataFrame(a).drop_duplicates().values
array([[ 0., 1.],
[ 0., 2.],
[ 0., 3.],
[ 1., 1.],
[ 1., 2.],
[ 1., 3.]])
每一行代表一个索引 (0, 1, 2, 3, 4 ,5)。为了获取数组a 中唯一行的索引,结果将是:
[0, 1, 2, 0, 1, 2, 0, 1, 2, 3, 4, 5, 3, 4, 5, 3, 4, 5]
我怎样才能以有效的方式得到这个结果?
【问题讨论】:
-
pd.DataFrame(a).drop_duplicates().index将返回原始 NP 数组中唯一行的索引 - 这是您想要的吗? -
不,这不是我想要的。这将返回唯一行首次出现的位置。
-
你好像在求多栏
factorize:看这个问答stackoverflow.com/questions/16453465/… -
是的,这就是我要找的。谢谢!
标签: python arrays numpy pandas