输入数据框:
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)
获取预期输出中所解释的值的最有效方法是什么?
最佳答案
您可以使用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])]
关于python - 从数据框列中获取数据作为元组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54535978/