-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspotify_streaming_analyzer.py
78 lines (67 loc) · 2.61 KB
/
spotify_streaming_analyzer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import pandas as pd
class SpotifyStreamingAnalyzer:
def __init__(self):
self.streaming = []
self.data_frame = None
self.grouped_data = None
def add_streaming_history(self, history):
"""
Add streaming history records to the streaming list
:param history: A list of streaming records
"""
self.streaming.extend(history)
def get_streaming_history(self):
"""
Get the streaming history list
:return: Current streaming history list
"""
return self.streaming
def get_data_frame(self):
"""
Get the dataframe used for analyzing
:return: Current dataframe
"""
return self.data_frame
def generate_data_frame(self):
"""
Generate DataFrame from streaming history
"""
self.data_frame = pd.DataFrame(self.streaming)
def filter_by_date(self, from_date):
"""
Filter streaming history before a specific date
:param from_date: The date to filter from (fromat: YYYY-MM-DD)
"""
filtered = self.data_frame[self.data_frame["endTime"] > from_date]
self.data_frame = filtered
def analyze(self):
"""
Analyze streaming history
"""
# Create pandas DataFrame from streaming list
# Group by tracks (identified by artist and track names)
self.grouped_data = self.data_frame.groupby(["artistName", "trackName"])
# Aggregate results
# Values are divided by 1000 to convert ms to seconds
self.grouped_data = self.grouped_data.agg(
{"msPlayed": ["count", lambda x: int(x.sum() / 1000), # TotalSecPlayed
lambda x: int((x.sum() / x.count()) / 1000), # AvgSecPerPlay
lambda x: int(x.max() / 1000), # MaxSecPlayed
lambda x: int(((max(x.sum() / x.count(), 1)) / max(1, x.max())) * 100)], # AvgPlayPercent
"endTime": ["min", "max"]})
# Rename columns
self.grouped_data.columns = ["Count", "TotalSecPlayed", "AvgSecPerPlay", "MaxSecPlayed", "AvgPlayPercent",
"FirstPlayed", "LastPlayed"]
def filter_by_play_count(self, count):
"""
Filter songs below a specific play count.
:param count: Minimum song play count
"""
filtered = self.grouped_data[self.grouped_data["Count"] >= count]
self.grouped_data = filtered
def get_result(self):
"""
Get the analyzed data
:return: DataFrame of the analyzed data
"""
return self.grouped_data