将离散列映射到其唯一值的索引

时间:2017-10-03 07:49:13

标签: python performance pandas numpy

我有一个带有int列的数据框:

df=pd.DataFrame(data=2*np.random.randint(0,high=10,size=5),columns=['N'])

    N
0   8
1   4
2   8
3  14
4   2
5  18

我想生成另一个数据框:

df2=

    N  ID
0   8  2  
1   4  1
2   8  2
3  14  3
4   2  0
5  18  4

其中ID是N

中唯一值的排序列表的索引

我需要一个计算上廉价的解决方案,因为它需要在大型数据帧上运行并经常更新。

2 个答案:

答案 0 :(得分:2)

使用np.unique及其可选的arg return_inverse -

非常简单
In [268]: df['ID'] = np.unique(df.N, return_inverse=1)[1]

In [269]: df
Out[269]: 
    N  ID
0   8   2
1   4   1
2   8   2
3  14   3
4   2   0
5  18   4

运行时测试(问题说它需要 - a computationally cheap solution) -

# Scale given sample 10,000 times in size and high-limit
In [373]: df=pd.DataFrame(data=2*np.random.randint(0,high=100000,size=50000),columns=['N'])

# @jezrael's soln
In [374]: %timeit df['ID1'] = df['N'].rank(method='dense').sub(1).astype(int)
100 loops, best of 3: 4.74 ms per loop

# Proposed in this post
In [376]: %timeit df['ID2'] = np.unique(df.N, return_inverse=1)[1]
100 loops, best of 3: 3.94 ms per loop

答案 1 :(得分:1)

使用rank + sub + astype

df['ID'] = df['N'].rank(method='dense').sub(1).astype(int)
print (df)
    N  ID
0   8   2
1   4   1
2   8   2
3  14   3
4   2   0
5  18   4