【发布时间】:2019-03-15 13:57:17
【问题描述】:
我在 Python 中有一个类似于以下内容的列表:
x = [1,2,2,3,3,3,4,4]
有没有办法使用 pandas 或其他一些列表推导使列表看起来像这样,类似于队列系统:
x = [1,2,3,4,2,3,4,3]
【问题讨论】:
标签: python pandas list duplicates unique
我在 Python 中有一个类似于以下内容的列表:
x = [1,2,2,3,3,3,4,4]
有没有办法使用 pandas 或其他一些列表推导使列表看起来像这样,类似于队列系统:
x = [1,2,3,4,2,3,4,3]
【问题讨论】:
标签: python pandas list duplicates unique
有可能,通过使用cumcount
s=pd.Series(x)
s.index=s.groupby(s).cumcount()
s.sort_index()
Out[11]:
0 1
0 2
0 3
0 4
1 2
1 3
1 4
2 3
dtype: int64
【讨论】:
如果您将列表拆分为每个值的单独列表 (groupby),则可以使用 itertools recipe roundrobin 获得此行为:
x = ([1, 2, 2, 3, 3, 3, 4, 4])
roundrobin(*(g for _, g in groupby(x)))
【讨论】:
如果我对您的理解正确,您希望保留所有重复项,然后按顺序排列列表,您可以在其中创建本质上是唯一值的单独列表,但它们都连接到一个列表中,按顺序。
我认为这在 listcomp 中是不可能的,而且我在 pandas 中轻松/快速地完成它并没有发生任何事情。
但简单的算法是:
【讨论】:
基本上你想要的是模式,这个模式只不过是我们在遍历list x 时找到唯一数字的顺序,例如:如果x = [4,3,1,3,5] 然后pattern = 4 3 1 5,现在这将帮助我们填写@987654324 @再次这样output will be [4,3,1,5,3]
from collections import defaultdict
x = [1,2,2,3,3,3,4,4]
counts_dict = defaultdict(int)
for p in x:
counts_dict[p]+=1
i =0
while i < len(x):
for p,cnt in counts_dict.items():
if i < len(x):
if cnt > 0:
x[i] = p
counts_dict[p]-=1
i+=1
else:
continue
else:
# we have placed all the 'p'
break
print(x) # [1, 2, 3, 4, 2, 3, 4, 3]
注意: python 3.6+ dict 尊重插入顺序,我假设您使用的是 python3.6+ 。
这是我一开始想做的,但在某些情况下它失败了..
'''
x = [3,7,7,7,4]
i = 1
while i < len(x):
if x[i] == x[i-1]:
x.append(x.pop(i))
i = max(1,i-1)
else:
i+=1
print(x) # [1, 2, 3, 4, 2, 3, 4, 3]
# x = [2,2,3,3,3,4,4]
# output [2, 3, 4, 2, 3, 4, 3]
# x = [3,7,1,7,4]
# output [3, 7, 1, 7, 4]
# x = [3,7,7,7,4]
# output time_out
'''
【讨论】: