I'm having the DataFrame that looks like this:
I need to convert it to the structure that looks like this:
{1234: [[(1504010302, 45678), (1504016546, 78908)], [(1506691286,23208)]],
4576: [[(1529577322, 789323)], [(1532173522, 1094738), (1532190922, 565980)]]}
So basically, I need to use the first-level index ('userID') as the key of the list of all sessions of a particular user and form distinct lists of particular sessions with page views as tuples based on the second-level index ('session_index'). I was trying to implement this solution: Convert dataframe to dictionary of list of tuples. But I couldn't figure out how to modify it to get the structure I need.
from datetime import datetime
# I'm creating the sample of different sessions
iterator = iter([{'user': 1234,
'timestamp': 1504010302,
'pageid': 45678},
{'user': 1234,
'timestamp': 1504016546,
'pageid':78908},
{'user': 1234,
'timestamp': 1506691286,
'pageid':23208}
,
{'user': 4567,
'timestamp': 1529577322,
'pageid': 789323},
{'user': 4567,
'timestamp': 1532173522,
'pageid': 1094738},
{'user': 4567,
'timestamp': 1532190922,
'pageid': 565980}])
# Then I'm creating an empty DataFrame
df = pd.DataFrame(columns=['userID', 'session_index', 'timestamp', 'pageid'])
# Then I'm filling the empty DataFrame based on the logic that I need to get in the final structure
for entry in iterator:
if not (df.userID == entry['user']).any():
df = df.append([{'userID': entry['user'], 'session_index': 1,
'timestamp': entry['timestamp'], 'pageid': entry['pageid']}],
ignore_index=True)
else:
session_numbers = df[(df.userID == entry['user'])
&
(df.timestamp.apply(lambda x: abs(datetime.fromtimestamp(x)
- datetime.fromtimestamp(entry['timestamp'])).days*24
+ abs(datetime.fromtimestamp(x)
- datetime.fromtimestamp(entry['timestamp'])).seconds // 3600
) <= 24)]
if len(session_numbers.session_index.values) == 0:
df = df.append([{'userID': entry['user'], 'session_index':
df.session_index[df.userID == entry['user']].max() + 1,
'timestamp': entry['timestamp'], 'pageid': entry['pageid']}],
ignore_index=True)
else:
df = df.append([{'userID': entry['user'], 'session_index': session_numbers.session_index.values[0],
'timestamp': entry['timestamp'], 'pageid': entry['pageid']}],
ignore_index=True)
# Then I'm setting the Multi Index
df = df.set_index(['userID', 'session_index'])
print(df.index)
# Then I'm trying to get t
new_dict = df.apply(tuple, axis=1)\
.groupby(level=0)\
.agg(lambda x: list(x.values))\
.to_dict()