我有两个列表:
index = [1,1,1,1,2,2,2,2,3,4,5,5,5,6,7,8,9,10,10,10]
value = [2,3,2,1,2,4,6,8,2,1,5,2,7,2,2,2,1,55,1,11]
长度相同,但我要返回的是索引列表中的唯一编号和根据索引的值列表的最小值
结果应类似于:
index_result = [1,2,3,4,5,6,7,8,9,10]
value_result = [1,2,2,1,2,2,2,2,1,1]
我尝试过:
index = [1,1,1,1,2,2,2,2,3,4,5,5,5,6,7,8,9,10,10,10]
value = [2,3,2,1,2,4,6,8,2,1,5,2,7,2,2,2,1,55,1,11]
index_result = []
value_result = []
#global small_value
j = 0
while j < len(index):
if j == 0:
try:
if index[j] == index[j+1]:
small_value = min(value[j],value[j+1])
elif index[j] != index[j+1]:
index_result.append(index[j])
value_result.append(value[j])
except IndexError as e:
print(e)
pass
j = j + 1
print('small value is for index j ==0')
print(small_value)
elif j <len(index) - 1:
try:
# if index[j] == index[j-1]:
# small_value = min(value[j],value[j-1])
if index[j] != index[j+1] and index[j] != index[j-1]:
index_result.append(index[j])
value_result.append(value[j])
elif index[j] != index[j+1] and index[j] == index[j-1]:
index_result.append(index[j])
value_result.append(small_value)
except IndexError as e:
print(e)
pass
j = j + 1
print('small value is for index 0 < j <len(index)')
print(small_value)
elif j == len(index) - 1:
try:
if index[j] == index[j-1]:
small_value = min(value[j],value[j-1])
index_result.append((index[j]))
value_result.append(small_value)
elif index[j] != index[j-1]:
index_result.append(index[j])
value_result.append(value[j])
except IndexError as e:
print(e)
pass
j = j + 1
print('small value is for j = len(index) - 1')
print(small_value)
print (index_result)
print (value_result)
结果接近预期但仍然错误:
[1、2、3、4、5、6、7、8、9、10] [2,2,2,1,2,2,2,2,1,1,1]
答案 0 :(得分:3)
自从标记了熊猫
pd.DataFrame([index,value]).T.sort_values([0,1]).drop_duplicates(0)
0 1
3 1 1
4 2 2
8 3 2
9 4 1
11 5 2
13 6 2
14 7 2
15 8 2
16 9 1
18 10 1
答案 1 :(得分:1)
我认为这是您想要实现的目标
<div class="header">
<span data-color="super">SUPER</span><span data-color="bone">BONE</span><span data-color="craft">CRAFT</span>
</div>
答案 2 :(得分:1)
如果您的index
如示例中所述单调递增,则可以使用itertools.groupby
from itertools import groupby
d = {k: min([x[1] for x in g]) for k, g in groupby(zip(index, value),
lambda x: x[0])}
In [95]: d
Out[95]: {1: 1, 2: 2, 3: 2, 4: 1, 5: 2, 6: 2, 7: 2, 8: 2, 9: 1, 10: 1}
index_result = list(d.keys())
Out[103]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
value_result = list(d.values())
Out[105]: [1, 2, 2, 1, 2, 2, 2, 2, 1, 1]
答案 3 :(得分:0)
Numpy解决方案:
index = np.array([1,1,1,1,2,2,2,2,3,4,5,5,5,6,7,8,9,10,10,10])
value = np.array([2,3,2,1,2,4,6,8,2,1,5,2,7,2,2,2,1,55,1,11])
[value[index == i].min() for i in np.unique(index)]
# [1, 2, 2, 1, 2, 2, 2, 2, 1, 1]