我有这样一个数据集:
user_id time_location
13 (2018-02-02, 190)
12 (2018-06-02, 194)
13 (2018-06-02, 194)
16 (2018-02-02, 190)
17 (2018-02-02, 190)
11 (2018-05-02, 198)
19 (2018-02-02, 190)
15 (2018-05-02, 198)
15 (2018-06-02, 194)
我想要的是一个字典列表,键是“time_location”列中的项目,值是每个键的 user_id 。这是一个示例输出:
List=[{(2018-02-02, 190): 13, 16,17,19},{(2018-06-02, 194): 12,13,15},{(2018-05-02, 198): 11,15}
谁能帮帮我?
最佳答案
一种方法是使用collections.defaultdict
:
from collections import defaultdict
df = pd.DataFrame({'user_id': [13, 12, 13, 16, 17, 11, 19, 15, 15],
'time_location': [('2018-02-02', 190), ('2018-06-02', 194),
('2018-06-02', 194), ('2018-02-02', 190),
('2018-02-02', 190), ('2018-05-02', 198),
('2018-02-02', 190), ('2018-05-02', 198),
('2018-06-02', 194)]})
d = defaultdict(list)
for idx, row in df.iterrows():
d[row['time_location']].append(row['user_id'])
d = [{k: v} for k, v in d.items()]
# [{('2018-02-02', 190): [13, 16, 17, 19]},
# {('2018-06-02', 194): [12, 13, 15]},
# {('2018-05-02', 198): [11, 15]}]
关于Python:制作包含两列项目的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49141005/