【发布时间】:2019-07-16 10:39:57
【问题描述】:
我有以下清单:
x = np.array([1, 1, 2, 2, 2])
np.unique 的值为[1, 2]
如何生成以下列表:
[1, 2, 1, 2, 3]
即列表 x 中每个唯一元素的从 1 开始的运行索引。
【问题讨论】:
标签: python numpy indexing unique
我有以下清单:
x = np.array([1, 1, 2, 2, 2])
np.unique 的值为[1, 2]
如何生成以下列表:
[1, 2, 1, 2, 3]
即列表 x 中每个唯一元素的从 1 开始的运行索引。
【问题讨论】:
标签: python numpy indexing unique
您可以在按值本身分组后使用pandas.cumcount(),它就是这样做的:
将每个组中的每个项目编号从 0 到该组的长度 - 1。
试试这个:
import numpy as np
import pandas as pd
x = np.array([1, 1, 2, 2, 2])
places = list(pd.Series(x).groupby(by=x).cumcount().values + 1)
print(places)
输出:
[1, 2, 1, 2, 3]
【讨论】:
list.index,这会慢100倍:(也许其他人只会想出一些numpy的东西。
只需将return_counts=True 的np.unique 与listcomp 和np.hstack 一起使用。它仍然是更快的 pandas 解决方案
c = np.unique(x, return_counts=True)[1]
np.hstack([np.arange(item)+1 for item in c])
Out[869]: array([1, 2, 1, 2, 3], dtype=int64)
【讨论】:
x = np.array([1, 1, 2, 2, 2, 1]),你会得到[1 2 3 1 2 3],而你应该得到[1 2 1 2 3 3]
我不确定,如果这是更快或更慢的解决方案,但如果你只需要一个没有熊猫的列表结果,你可以试试这个
arr = np.array([1, 1, 2, 2, 2])
from collections import Counter
ranges = [range(1,v+1) for k,v in Counter(arr).items()]
result = []
for l in ranges:
result.extend(list(l))
print(result)
[1, 2, 1, 2, 3]
(或使用dict 而不是Counter() 制作自己的计数器)
【讨论】: