python - 从没有唯一索引的数据帧生成时间序列序列
问题描述
我有一个来自 csv 的数据框,其中包含以下列:user_id、path、timestamp、gender
| user_id | path | timestamp | gender |
|:-------: |------ |--------------------- |-------- |
| 0 | 1 | 2017-01-01 01:08:56 | f |
| 0 | 2 | 2017-01-01 01:07:56 | f |
| 0 | 3 | 2017-01-01 01:08:40 | f |
| 0 | 4 | 2017-01-01 01:04:36 | f |
| 0 | 5 | 2017-01-01 01:09:53 | f |
| 0 | 6 | 2017-01-01 01:12:33 | f |
| 0 | 7 | 2017-01-01 01:14:12 | f |
| 0 | 8 | 2017-01-01 01:16:25 | f |
| 0 | 9 | 2017-01-01 01:16:56 | f |
| 1 | 1 | 2017-01-01 01:08:56 | m |
| 1 | 2 | 2017-01-01 01:08:06 | m |
| 1 | 3 | 2017-01-01 01:10:51 | m |
| 1 | 4 | 2017-01-01 01:13:53 | m |
| 2 | 1 | 2017-01-01 01:08:56 | f |
| 3 | 2 | 2017-01-01 01:34:56 | m |
输出应该是这样的一系列元素:
| paths | timestamps | gender |
|------------------- |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-------- |
| 1,2,3,4,5,6,7,8,9 | 2017-01-01 01:08:56, 2017-01-01 01:07:56, 2017-01-01 01:08:40, 2017-01-01 01:04:36, 2017-01-01 01:09:53, 2017-01-01 01:12:33, 2017-01-01 01:14:12, 2017-01-01 01:16:25, 2017-01-01 01:16:56 | f |
问题是来自不同时间戳的同一个 user_id 有多行,我需要一个序列用于时间序列分类(根据路径预测性别)。此外,时间戳在整个数据帧中并不是唯一的,但它们适用于每个用户。
我首先尝试使用带有以下代码的 pandas groupby 函数
dictionary = {}
for name, group in grouped:
index = name[0]
if dictionary.get(index, -1) == -1:
dictionary[index] = {"sequence": group.path.values, "timestamps": group.timestamp.values, "gender": group.gender.values[0]}
else:
dictionary[index]["sequence"] = [dictionary[index]["sequence"], group.path.values]
这实际上不起作用,因为我无法取出值(它保持多索引)并且我无法从每个组中提取值。
此外,我使用以下代码片段进行了尝试:
dictionary = {}
for name, group in grouped:
index = name[0]
if dictionary.get(index, -1) == -1:
dictionary[index] = {"sequence": group.path.values, "timestamps": group.timestamp.values, "gender": group.gender.values[0]}
else:
dictionary[index]["sequence"] = [dictionary[index]["sequence"], group.path.values]
谢谢你的帮助!