[英]How can I remove duplicates in a list and change their corresponding values in another list (by index position) to the mean?
假设我有两个列表:
list1 = [1200,1200,1200,2000]
list2 = [12000,14000,13000,30000]
如何删除list1中的重复项并取list2中所有对应值的平均值? 例如,1200 匹配 12000,1200 匹配 14000 和 1200 匹配 13000 --> 删除重复的 1200 并取 (12000,14000 和 13000) 的平均值并返回它们在 list2 (13000) 中的位置。 这应该产生:
list1new = [1200,2000]
list2new = [13000,30000]
谢谢
尝试:
from statistics import mean
list1 = [1200, 1200, 1200, 2000]
list2 = [12000, 14000, 13000, 30000]
tmp = {}
for a, b in zip(list1, list2):
tmp.setdefault(a, []).append(b)
list1new, list2new = [], []
for k, v in tmp.items():
list1new.append(k)
list2new.append(mean(v))
print(list1new)
print(list2new)
印刷:
[1200, 2000]
[13000, 30000]
import pandas as pd
df = pd.DataFrame({'l1':list1, 'l2': list2})
tmp = df.groupby('l1')['l2'].mean()
new_list1 = list(tmp.index)
new_list2 = list(tmp)
print(new_list1)
print(new_list2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.