好像你需要groupby
索引
df.groupby(level='Id').apply(lambda x : x.set_index('product').T.to_dict(orient='records'))
Out[124]:
Id
175 [{''409'': 41, ''407'': 8, ''0.5L'': 4, ''1.5L...
177 [{''SCHWEPPES'': 6, ''TONIC1L'': 4}]
dtype: object
输出列表
df.groupby(level='Id').apply(lambda x : x.set_index('product').T.to_dict(orient='records')).tolist()
Out[128]:
[[{"'0.5L'": 4, "'1.5L'": 4, "'407'": 8, "'409'": 41}],
[{"'SCHWEPPES'": 6, "'TONIC1L'": 4}]]
制作一个平面列表
ll=df.groupby(level='Id').apply(lambda x : x.set_index('product').T.to_dict(orient='records')).tolist()
import operator
import functools
functools.reduce(operator.concat, ll)
Out[130]:
[{"'0.5L'": 4, "'1.5L'": 4, "'407'": 8, "'409'": 41},
{"'SCHWEPPES'": 6, "'TONIC1L'": 4}]
来源
2017-10-12 20:25:41
Wen