Certainly! I'd be happy to help you work through these data analysis tasks using Pandas and SQL. Since these tasks are based on analyzing a dataset of support ticket logs, I'll provide step-by-step guidance on how to approach each question. You'll need to adjust the code according to your actual data.
General Setup
First, let's assume you have a CSV file named support_questions.csv containing the logs. We'll start by importing the necessary libraries and loading the data into a Pandas DataFrame.
import pandas as pd
# Load the data
df = pd.read_csv('support_questions.csv')
# Ensure the datetime fields are correctly parsed
df['time'] = pd.to_datetime(df['time'])
Now, let's address each task one by one.
Задание 1: Тикеты, ожидающие обработки (10 баллов)
Task: Calculate the number of tickets that are currently awaiting processing by an agent. Use the status field:
1 — ticket has been processed,
- any other value — ticket requires processing.
If at the same timestamp there are multiple logs with different statuses for one ticket, ignore the rows with status 1.
Approach:
- Sort the DataFrame by
question_id and time to ensure chronological order.
- Group by
question_id and get the latest events for each ticket.
- Handle duplicate timestamps: For entries with the same
question_id and time, if any status is not 1, exclude the ones with status 1.
- Filter tickets where the latest status is not
1.
- Count the number of such tickets.
Code:
# Sort by question_id and time
df_sorted = df.sort_values(['question_id', 'time'])
# Identify duplicates at the latest time per question_id
latest_time = df.groupby('question_id')['time'].max().reset_index()
df_latest = pd.merge(df, latest_time, on=['question_id', 'time'], how='inner')
# For duplicate times per question_id, exclude status 1 if other statuses exist
df_latest = df_latest.sort_values(by=['question_id', 'status'])
df_latest_no1 = df_latest[df_latest['status'] != 1]
df_latest = pd.concat([df_latest_no1, df_latest[~df_latest['question_id'].isin(df_latest_no1['question_id'])]])
# Filter tickets where the latest status is not 1
tickets_awaiting = df_latest[df_latest['status'] != 1]['question_id'].nunique()
print(f"Number of tickets awaiting processing: {tickets_awaiting}")
Задание 2: Удалённые сообщения (5 баллов)
Task: Determine who deletes messages more often and in what quantity. Calculate how many messages were deleted by employees and how many by users. Choose the group that deletes messages more often and specify the number of messages deleted by that group.
Approach:
- Filter events where messages are deleted. This can be events where
event_type is something like 'delete_message'.
- Group by
user_type and count the deletions.
- Compare the counts and identify the group with more deletions.
Code:
# Filter events where messages are deleted
deleted_messages = df[df['event_type'] == 'message_deleted']
# Count deletions by user_type
deletions_count = deleted_messages['user_type'].value_counts()
# Determine who deletes more messages
max_deletions = deletions_count.max()
group_with_max_deletions = deletions_count.idxmax()
print(f"The group that deletes messages more often: {group_with_max_deletions}")
print(f"Number of messages deleted by them: {max_deletions}")
Answer: Provide the number corresponding to the group with the higher count.
Задание 3: Повторные вопросы после закрытия по причине «троллинг» (5 баллов)
Task: Determine the number of tickets where, after the event event_type = 'troll_closed', the user asked a new question (reply).
Approach:
- Identify tickets with the
'troll_closed' event.
- Check if there's any
'reply' event after the 'troll_closed' event in the same ticket.
- Count the number of such tickets.
Code:
# Initialize a list to store question_ids
question_ids = []
# Group by question_id
for question_id, group in df.groupby('question_id'):
group = group.sort_values('time')
troll_closed_time = group[group['event_type'] == 'troll_closed']['time']
if not troll_closed_time.empty:
# Get the first troll_closed event time
troll_closed_time = troll_closed_time.iloc[0]
# Check for any 'reply' events after troll_closed_time
replies_after = group[(group['event_type'] == 'reply') & (group['time'] > troll_closed_time)]
if not replies_after.empty:
question_ids.append(question_id)
num_tickets = len(question_ids)
print(f"Number of tickets where user replied after 'troll_closed': {num_tickets}")
Задание 4: Анализ тегов тикетов (10 баллов)
Task: Count the number of tickets by tags, where a tag is defined as event_subtype LIKE 'tag_%'. Consider only the last tag in each ticket (1 ticket — 1 tag). Provide the most popular tag.
Approach:
- Filter events where
event_subtype matches 'tag_%'.
- Group by
question_id and get the last tag for each ticket.
- Count the occurrences of each tag.
- Identify the most popular tag.
Code:
# Filter events with tags
tags_df = df[df['event_subtype'].str.startswith('tag_')]
# Get the last tag per ticket
last_tags = tags_df.sort_values('time').groupby('question_id').tail(1)
# Count the tags
tag_counts = last_tags['event_subtype'].value_counts()
# Get the most popular tag
most_popular_tag = tag_counts.idxmax()
print(f"The most popular tag is: {most_popular_tag}")
Задание 5: Тег, который чаще всего ставят агенты (5 баллов)
Task: Output the tag (event_subtype) that agents most frequently assign to tickets. Consider only events with event_type = 'tag_set_manually'.
Approach:
- Filter events where
event_type is 'tag_set_manually'.
- Assuming agents are the ones performing these events.
- Count the occurrences of each tag in
event_subtype.
- Identify the most frequent tag.
Code:
# Filter events set manually by agents
agent_tags = df[df['event_type'] == 'tag_set_manually']
# Count the tags
agent_tag_counts = agent_tags['event_subtype'].value_counts()
# Get the most frequent tag
most_frequent_agent_tag = agent_tag_counts.idxmax()
print(f"The tag most frequently set by agents is: {most_frequent_agent_tag}")
Задание 6: Изменение категории тикета со статусом 0 (5 баллов)
Task: Output the ticket number (question_id) where there's an event event_type = 'set_category', and at the time of the event, the ticket's status was 0.
Approach:
- Filter events where
event_type is 'set_category'.
- Check the
status in these events.
- Find the tickets where
status is 0.
- Output the
question_id.
Code:
# Filter events where the category is set and status is 0
category_changes = df[(df['event_type'] == 'set_category') & (df['status'] == 0)]
# Get the question_id(s)
question_ids = category_changes['question_id'].unique()
print(f"Question IDs with set_category and status 0: {question_ids}")
Задание 7: Расчет UWT (15 баллов)
Task: Calculate the User Waiting Time (UWT) - the average time a user waits for a response from an agent. UWT is calculated based on "user question" -> "agent response" chains.
Approach:
- Exclude deleted messages.
- Identify chains where a user's
'reply' is followed by an agent's 'agent_reply'.
- Ensure if there are multiple user replies or agent replies in a row, only consider the first user reply and the first agent reply that follows.
- Calculate the time difference between the user's question and the agent's response.
- Compute the average waiting time.
Code:
# Exclude deleted messages
df_non_deleted = df[df['event_type'] != 'message_deleted']
# Sort by question_id and time
df_non_deleted = df_non_deleted.sort_values(['question_id', 'time'])
# Initialize a list to store waiting times
waiting_times = []
# Process each ticket
for question_id, group in df_non_deleted.groupby('question_id'):
group = group.reset_index(drop=True)
i = 0
while i < len(group):
if group.loc[i, 'event_type'] == 'reply':
user_time = group.loc[i, 'time']
# Find the next agent_reply
agent_replies = group[(group.index > i) & (group['event_type'] == 'agent_reply')]
if not agent_replies.empty:
agent_time = agent_replies.iloc[0]['time']
wt = (agent_time - user_time).total_seconds()
waiting_times.append(wt)
# Move index to after the agent reply
i = agent_replies.index[0]
else:
break # No agent reply after user's reply
i += 1
# Calculate average waiting time
average_uwt = sum(waiting_times) / len(waiting_times)
print(f"Average User Waiting Time (UWT): {average_uwt:.2f} seconds")
Задание 8: Расчёт SL (15 баллов)
Task: Calculate the Service Level (SL) - the percentage of responses given within the target time (15 minutes). SL = (number of chains with UWT ≤ 15 minutes / total number of chains) * 100%
Approach:
- Use the waiting times calculated in the previous task.
- Count the total number of chains.
- Count the number of chains where the waiting time is ≤ 15 minutes (900 seconds).
- Calculate the SL percentage.
Code:
# Using waiting_times from previous task
total_chains = len(waiting_times)
chains_within_15min = sum(1 for wt in waiting_times if wt <= 900) # 900 seconds = 15 minutes
sl = (chains_within_15min / total_chains) * 100
print(f"Service Level (SL): {sl:.2f}%")
Задание 9: Определение скорости ответа сотрудников (10 баллов)
Task: Determine which group of employees (by user_type) provides the fastest responses to user questions. Calculate the average response time for each group and identify the group with the lowest average.
Approach:
- Modify the process from Task 7 to include
user_type of the responding agent.
- Group the waiting times by
user_type.
- Calculate the average response time per
user_type.
- Identify the
user_type with the minimum average response time.
Code:
# Initialize a dict to store waiting times per user_type
waiting_times_by_user_type = {}
# Process each ticket
for question_id, group in df_non_deleted.groupby('question_id'):
group = group.reset_index(drop=True)
i = 0
while i < len(group):
if group.loc[i, 'event_type'] == 'reply':
user_time = group.loc[i, 'time']
# Find the next agent_reply
agent_replies = group[(group.index > i) & (group['event_type'] == 'agent_reply')]
if not agent_replies.empty:
agent_reply = agent_replies.iloc[0]
agent_time = agent_reply['time']
wt = (agent_time - user_time).total_seconds()
agent_user_type = agent_reply['user_type']
if agent_user_type not in waiting_times_by_user_type:
waiting_times_by_user_type[agent_user_type] = []
waiting_times_by_user_type[agent_user_type].append(wt)
# Move index to after the agent reply
i = agent_replies.index[0]
else:
break # No agent reply after user's reply
i += 1
# Calculate average response time per user_type
avg_response_times = {}
for user_type, times in waiting_times_by_user_type.items():
avg_response_times[user_type] = sum(times) / len(times)
# Identify the user_type with the lowest average response time
fastest_user_type = min(avg_response_times, key=avg_response_times.get)
print(f"Simplest user_type with fastest responses: {fastest_user_type}")
print(f"Average response time: {avg_response_times[fastest_user_type]:.2f} seconds")
Задание 10: Время до закрытия тикета (10 баллов)
Task: Calculate the average time from the last action in the ticket to when it's closed due to timeout (event_type = 'closed_by_time'). Use only actions that occurred before the 'closed_by_time' event. If there are multiple 'closed_by_time' events, use the last one. Provide the average number of days.
Approach:
- Identify tickets with the
'closed_by_time' event.
- For each ticket, find the time of the last
'closed_by_time' event.
- Find the last action before this event.
- Calculate the time difference between the last action and the
'closed_by_time' event.
- Compute the average time in days.
Code:
from datetime import timedelta
# Initialize a list to store time differences
time_diffs = []
# Process each ticket
for question_id, group in df.groupby('question_id'):
group = group.sort_values('time')
closed_times = group[group['event_type'] == 'closed_by_time']['time']
if not closed_times.empty:
closed_time = closed_times.iloc[-1] # Last 'closed_by_time' event
actions_before_closed = group[group['time'] < closed_time]
if not actions_before_closed.empty:
last_action_time = actions_before_closed.iloc[-1]['time']
diff = (closed_time - last_action_time).total_seconds() / (24 * 3600) # Convert to days
time_diffs.append(diff)
# Calculate average time difference
average_diff_days = sum(time_diffs) / len(time_diffs)
print(f"Average time from last action to ticket closure: {average_diff_days:.2f} days")
Задание 11: Время между назначением и сбросом агента (10 баллов)
Task: Calculate the average time from when an employee is assigned (event_type = 'set_agent') to when they are dropped (event_type = 'drop_agent'). Use only the nearest events to each other. Exclude drops initiated by users.
Approach:
- Filter events with
event_type 'set_agent' and 'drop_agent'.
- Exclude any
drop_agent events initiated by users (you might need to check another field to determine who initiated it).
- For each ticket, match the last
'set_agent' event before a 'drop_agent'.
- Calculate the time differences.
- Compute the average time in seconds.
Code:
# Initialize a list to store time differences
agent_times = []
# Assuming there's a field 'initiator' to check who initiated the drop
# Process each ticket
for question_id, group in df.groupby('question_id'):
group = group.sort_values('time')
set_agents = group[group['event_type'] == 'set_agent']
drop_agents = group[group['event_type'] == 'drop_agent']
# Exclude drops initiated by users
drop_agents = drop_agents[drop_agents['initiator'] != 'user']
while not set_agents.empty and not drop_agents.empty:
set_agent_time = set_agents.iloc[-1]['time'] # Last set_agent
drop_agent_time = drop_agents.iloc[0]['time'] # First drop_agent
if set_agent_time < drop_agent_time:
diff = (drop_agent_time - set_agent_time).total_seconds()
agent_times.append(diff)
# Remove used entries
set_agents = set_agents.iloc[:-1]
drop_agents = drop_agents.iloc[1:]
else:
break
# Calculate average time
average_agent_time = sum(agent_times) / len(agent_times)
print(f"Average time between set_agent and drop_agent: {average_agent_time:.2f} seconds")
Final Submission:
After computing the answers for each task, prepare a text file with the question numbers and the corresponding answers. Each line should contain a question number and the answer separated by a comma.
Example:
1, 123
2, 45
3, 67
...
Replace the numbers with the actual results you obtained from your calculations.
Note: Adjust the code snippets to match your actual data, especially the column names and any additional fields that might be necessary for certain computations (like identifying who initiated an event).
If you need any further clarification or assistance with specific parts of the code, feel free to ask!