输入数据框:
id value
0 0 10.2
1 1 5.7
2 2 7.4
3 2 2.5
4 1 2.6
5 3 1.6
6 2 2.9
7 0 3.6
8 2 2.7
预期输出:
format : [(id,count_of_value,[value as a list])] i.e like this
[ (0,2,[10.2, 3.6]), (1, 2, [5.7, 2.6]). . ]
到目前为止,我已经能够获取前两个元素,即id,并且它被视为一个元组。此外,我还需要以相反的顺序排列数据,
id_list = df.id.tolist()
count = Counter(uid_list)
ID_count_list = sorted(count.items(), key=operator.itemgetter(1),reverse=True)
获得预期输出中解释的值的最有效方法是什么?
答案 0 :(得分:2)
您可以使用groupby + apply一步完成所有操作,匹配所需的输出:
result = df.groupby('id')['value'].apply(lambda x: (x.name, x.size, x.tolist())).tolist()
print(result)
输出
[(0, 2, [10.2, 3.6]), (1, 2, [5.7, 2.6]), (2, 4, [7.4, 2.5, 2.9, 2.7]), (3, 1, [1.6])]
鉴于上面的输出,您可以像这样进行排序:
result = [(0, 2, [10.2, 3.6]), (1, 2, [5.7, 2.6]), (2, 4, [7.4, 2.5, 2.9, 2.7]), (3, 1, [1.6])]
s = sorted(result, key=operator.itemgetter(1), reverse=True)
print(s)
输出 (已排序)
[(2, 4, [7.4, 2.5, 2.9, 2.7]), (0, 2, [10.2, 3.6]), (1, 2, [5.7, 2.6]), (3, 1, [1.6])]
答案 1 :(得分:1)
这是一个groupby
问题。如果列表列表足够:
res = df.groupby('id')['value'].agg(['count', lambda x: x.tolist()])\
.reset_index().values.tolist()
print(res)
# [[0, 2, [10.2, 3.6]], [1, 2, [5.7, 2.6]],
# [2, 4, [7.4, 2.5, 2.9, 2.7]], [3, 1, [1.6]]]
有关元组的列表,还有一个附加步骤:
res = list(map(tuple, res))
print(res)
# [(0, 2, [10.2, 3.6]), (1, 2, [5.7, 2.6]),
# (2, 4, [7.4, 2.5, 2.9, 2.7]), (3, 1, [1.6])]