Python:制作一个包含两列项的字典
我有这样一个数据集:Python:制作一个包含两列项的字典,python,list,pandas,dictionary,group-by,Python,List,Pandas,Dictionary,Group By,我有这样一个数据集: 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) 1
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)
我想要的是一个字典列表,其中键是“时间位置”列中的项,值是每个键的用户id。以下是一个示例输出:
List=[{(2018-02-02, 190): 13, 16,17,19},{(2018-06-02, 194): 12,13,15},{(2018-05-02, 198): 11,15}
有人能帮我吗?试试这个:
listOfDict = []
for pair in your_dataset: ## I'm assuming your data is a list of lists/tuples
listOfDict.append({pair[1]: pair[0]})
您也可以使用
groupby
df.groupby("time_location")["user_id"].apply(list).to_dict()
一种方法是使用
df.groupby()
:
一种方法是使用集合。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]}]
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]}]