1
vkhsyj 2019-12-01 00:39:29 +08:00 1
一个思路,按照 name 进行 groupby,然后每个分组加起来
|
2
hutng 2019-12-01 00:41:01 +08:00 via Android 1
笨办法:for 循环遍历
聪明办法:不知道 |
3
yang3yen 2019-12-01 00:47:47 +08:00 1
info = [
{'name': 'apple', 'value': 2, 'package': 3}, {'name': 'orange', 'value': 5, 'package': 4}, {'name': 'apple', 'value': 5, 'package': 5} ] # 要保持原来的顺序,可使用 collections.OrderedDict info_d = {} for v in info: if v['name'] not in info_d: info_d[v['name']] = v else: d = info_d[v['name']] d['value'] += v['value'] d['package'] += v['package'] info = info_d.values() |
4
zhzy 2019-12-01 00:52:10 +08:00 via iPhone 1
可以直接用==判断字典是否相同
|
5
di94sh 2019-12-01 00:59:26 +08:00 via iPhone 1
Pandas group by 再 sum 和 sql 一样
|
6
widewing 2019-12-01 04:20:46 +08:00 via Android 1
from itertools import groupby, reduce
|
7
di94sh 2019-12-01 05:13:58 +08:00 1
```python
import pandas as pd rows = [{'name': 'apple', 'value': 2, 'package': 3}, {'name': 'orange', 'value': 5, 'package': 4}, {'name': 'apple', 'value': 5, 'package': 5}] df = pd.DataFrame(rows) s = df.groupby('name', as_index=False).agg({'value': 'sum', 'package': 'sum'}) l = s.T.to_dict().values() print(list(l)) ``` |
8
yucongo 2019-12-01 11:02:12 +08:00
# 我来学习一下 groupby 的用法
import numpy as np from itertools import groupby info = [{'name':'apple','value':2,'package':3},{'name':'orange','value':5,'package':4},{'name':'apple','value':5,'package':5}] lst = [[key, [*np.asarray([[*elm.values()][1:] for elm in group]).sum(axis=0)]] for key, group in groupby(sorted(info, key=lambda x: x.get('name')), lambda x: x.get('name'))] # ->[['apple', [7, 8]], ['orange', [5, 4]]] [{**dict(zip([*info[0].keys()][:1], elm[:1])), **dict(zip([*info[0].keys()][1:], elm[1:][0]))} for elm in lst] # ->[{'name': 'apple', 'value': 7, 'package': 8}, {'name': 'orange', 'value': 5, 'package': 4}] |
9
Pzqqt 2019-12-01 11:09:34 +08:00 via Android
可以阅读这篇文章
http://148.70.149.207/entry/6 |
10
ddzzhen 2019-12-01 12:59:30 +08:00 via Android
如果 name,value,package 都是一样的,不如换列表方便
|
11
pengdirect 2019-12-01 17:55:24 +08:00 via iPhone
python pandas 的透视函数可以帮到你
|
12
cy18 2019-12-01 20:18:31 +08:00 via Android
字典已经 O ( 1 )了,直接循环,又简单又快
|