首页 > 解决方案 > 熊猫:按顺序将唯一值返回到列

问题描述

我不确定在这种情况下我应该如何进行。

考虑像下面这样的df,当我这样做时df.A.unique()->给我一个这样的数组[1, 2, 3, 4]

但我也想要这个值的索引,比如numpy.unique()

df = pd.DataFrame({'A': [1,1,1,2,2,2,3,3,4], 'B':[9,8,7,6,5,4,3,2,1]})
df.A.unique()
>>> array([1, 2, 3, 4])

np.unique([1,1,1,2,2,2,3,3,4], return_inverse=True)
>>> (array([1, 2, 3, 4]), array([0, 0, 0, 1, 1, 1, 2, 2, 3]))

我怎样才能在熊猫中做到这一点?带索引的唯一值。

标签: pythonpandasunique

解决方案


pandas我们有drop_duplicates

df.A.drop_duplicates()
Out[22]: 
0    1
3    2
6    3
8    4
Name: A, dtype: int64

匹配np.unique输出factorize

pd.factorize(df.A)
Out[21]: (array([0, 0, 0, 1, 1, 1, 2, 2, 3]), Int64Index([1, 2, 3, 4], dtype='int64'))

推荐阅读