python - 从数据框列中获取数据作为元组列表

标签 python pandas list dataframe pandas-groupby

输入数据框:

    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/

相关文章:

Python UnicodeEncodeError,但我已将参数编码为 UTF-8

python - 在 Python 中实现类似 shell 的管道性能

python - Google BigQuery Schema 冲突(pyarrow 错误)与使用 load_table_from_dataframe 的数字数据类型

python - list.remove() 方法未提供预期结果

python - 具有顺序限制的两个列表的元素的排列

python - django nginx 在生产中通过 http 获取 csrf 验证错误

python - Json 'list' 对象没有属性 'get'

python - 遍历行时如何使用掩码更新 DataFrame 中的值

python - pandas列astype错误: TypeError: Cannot cast Index to dtype datetime64[D]

python - Python 中的列表范围 - Project Euler 007