Анализ данных службы поддержки позволяет оценивать качество работы сотрудников, улучшать процессы взаимодействия с пользователем и находить проблемные области. Вам предстоит выступить в качестве аналитика данных и решить задания на основе реальных данных пользовательских обращений. Вы можете использовать SQL, Pandas и другие инструменты для расчета показателей, которые помогут улучшить качество обслуживания клиентов и эффективность работы системы поддержки.
В качестве решения загрузите текстовый файл, содержащий номера вопросов и ответы на них (в одной строке - один вопрос, разделитель - запятая). Если вы решили только часть заданий, то укажите в файле номера и ответы только для этих вопросов. Пример файла с форматом отправки решение - sample_submission.txt
Максимальный балл за задачу - 100.
Задание 1: Тикеты, ожидающие обработки (10 баллов)
Необходимо вывести количество тикетов, которые на данный момент ожидают отработки агентом. Для этого используйте поле status:
1 — тикет отработан,
любое другое значение — тикет требует отработки.
Если в один и тот же момент времени записано несколько логов с разными статусами для одного тикета, строки со статусом 1 не учитываются.
Задание 2: Удалённые сообщения (5 баллов)
Определите, кто удаляет сообщения чаще и в каком количестве. Рассчитайте, сколько сообщений было удалено сотрудниками, а сколько — пользователями. Выберите тех, кто удаляет сообщения чаще. В ответе укажите одно число — количество удаленных сообщений выбранной группой.
Задание 3: Повторные вопросы после закрытия по причине «троллинг» (5 баллов)
Определите количество тикетов, в которых после события event_type = 'troll_closed' пользователь задал новый вопрос (reply).
Задание 4: Анализ тегов тикетов (10 баллов)
Посчитайте количество тикетов в разрезе тегов, где тег определяется как event_subtype LIKE 'tag_%'. Учитывайте только последний тег в каждом тикете (1 тикет — 1 тег). В ответе укажите самый популярный тег.
Задание 5: Тег, который чаще всего ставят агенты (5 баллов)
Выведите тег (event_subtype), который чаще всего ставят агенты в тикетах. Рассматривайте только события с типом event_type = 'tag_set_manually' (значения в других столбцах могут быть любыми).
Задание 6: Изменение категории тикета со статусом 0 (5 баллов)
Выведите номер тикета (question_id), в котором есть запись event_type = 'set_category', если на момент записи статус тикета (status) был равен 0.
Задание 7: Расчет UWT (15)
Необходимо рассчитать показатель User Waiting Time (UWT) - среднего времени ожидания пользователем ответа сотрудника. Показатель рассчитывается на основании данных из таблицы support_questions, где фиксируются цепочки взаимодействий "вопрос пользователя" -> "ответ сотрудника". В ответе укажите среднее время в секундах с точностью до сотых.
UWT = среднее время ожидания пользователя по всем цепочкам "вопрос пользователя" -> "ответ сотрудника" за период.
Примечания:
В качестве ответа агента необходимо учитывать строки, где event_type = 'agent_reply' (с любыми значениями в других столбцах).
В качестве вопроса пользователя необходимо учитывать строки, где event_type = ‘reply’ (с любыми значениями в других столбцах).
Пользователь может написать 2 и более вопроса подряд, в этом случае учитывается вопрос, который задан раньше.
Сотрудник может дать 2 и более ответа подряд, в этом случае учитывается ответ, который дан раньше.
Удаленные вопросы и ответы исключаются из расчета.
Assistant
Задание 8: Расчёт SL (15 баллов)
Необходимо рассчитать показатель Service Level (SL) - процент ответов, данных в течение целевого времени (15 минут). Показатель рассчитывается на основании данных из таблицы support_questions, где фиксируются цепочки взаимодействий "вопрос пользователя" -> "ответ сотрудника". В ответе укажите значение с точностью до сотых.
SL = (количество цепочек с UWT ≤ 15 минут / общее количество цепочек) * 100%
Примечания:
В качестве ответа агента необходимо учитывать строки, где event_type = 'agent_reply' (с любыми значениями в других столбцах).
В качестве вопроса пользователя необходимо учитывать строки, где event_type = ‘reply’ (с любыми значениями в других столбцах).
Пользователь может написать 2 и более вопроса подряд, в этом случае учитывается вопрос, который задан раньше.
Сотрудник может дать 2 и более ответа подряд, в этом случае учитывается ответ, который дан раньше.
Удаленные вопросы и ответы исключаются из расчета.
Задание 9: Определение скорости ответа сотрудников (10 баллов)
Определите, сотрудники с каким значением поля user_type дают самые быстрые ответы на вопросы пользователей. Для этого нужно рассчитать среднее (mean) время ответа для каждой группы сотрудников и определить группу с наименьшим средним временем ответа.
В качестве ответа агента необходимо учитывать строки, где event_type = 'agent_reply' (с любыми значениями в других столбцах). В качестве вопроса пользователя необходимо учитывать строки, где event_type = ‘reply’ (с любыми значениями в других столбцах).
Задание 10: Время до закрытия тикета (10 баллов)
Посчитайте среднее время от последнего действия в тикете до его закрытия по таймауту. Используйте только действия, которые произошли до события с типом event_type = 'closed_by_time'. Если в тикете было несколько таких событий, используйте последнее из них. В ответе дайте среднее (mean) количество дней с точностью до сотых.
Примечание: исключите из расчета действия, которые произошли после закрытия по таймауту.
Задание 11: Время между назначением и сбросом агента (10 баллов)
Посчитайте среднее время от назначения сотрудника до сброса (от event_type = 'set_agent' до event_type = 'drop_agent'). В ответе укажите среднее (mean) время в секундах с точностью до сотых.
Примечания:
Учитывайте только ближайшие друг к другу события. Если было несколько событий set_agent и/или drop_agent подряд, берите последний set_agent и первый drop_agent.
Исключите из расчета сбросы, инициированные пользователями.
Файлы
SQL_data.xlsx
sample_submission.txt
Реши с помощью Python. В шапке таблицы time, tags, question_id, event_type, nav_screen, event_subtype, agent_role, status, user_type, reply_id
To solve these data analysis tasks using Python, we'll use the pandas library to manipulate and analyze the data provided in the SQL_data.xlsx file. Below is the Python code that addresses each of the questions step by step.
First, let's start by importing the necessary libraries and reading the data:
python
import pandas as pd
import numpy as np
# Read the data from the Excel file
df = pd.read_excel('SQL_data.xlsx')
# Convert 'time' column to datetime format if it's not already
df['time'] = pd.to_datetime(df['time'])
Now, we'll proceed to solve each question individually.
Question 1: Tickets Awaiting Processing
Objective: Count the number of tickets currently awaiting agent processing. Use the status field:
1 — ticket processed
Any other value — ticket requires processing.
If multiple logs at the same time with different statuses for the same ticket exist, lines with status = 1 are not considered.
Solution:
python
# Sort the DataFrame by 'question_id' and 'time'
df_sorted = df.sort_values(['question_id', 'time'])
# Get the latest time for each 'question_id'
latest_times = df_sorted.groupby('question_id')['time'].max().reset_index()
# Merge to get the latest entries for each 'question_id'
df_latest = pd.merge(latest_times, df_sorted, on=['question_id', 'time'])
# For entries with duplicate 'question_id' and 'time', ignore rows where 'status' == 1
df_latest = df_latest[df_latest['status'] != 1]
# The tickets awaiting processing are the unique 'question_id's left
tickets_awaiting = df_latest['question_id'].nunique()
print("Number of tickets awaiting processing:", tickets_awaiting)
Question 2: Deleted Messages
Objective: Determine who deletes messages more often (employees or users) and the number of messages deleted by them. Provide the count for the group that deletes more messages.
Solution:
python
# Filter events where messages are deleted
deleted_messages = df[df['event_type'] == 'delete_reply']
# Count deletions by 'user_type'
deletions_by_user_type = deleted_messages['user_type'].value_counts()
# Identify who deletes more messages
max_deletions = deletions_by_user_type.max()
group_who_deletes_more = deletions_by_user_type.idxmax()
print(f"{group_who_deletes_more} delete messages more often, with {max_deletions} deletions.")
Question 3: Repeat Questions After Closure Due to 'Trolling'
Objective: Count the number of tickets where, after an event event_type = 'troll_closed', the user asked a new question (event_type = 'reply').
Solution:
python
# Initialize a counter
ticket_count = 0
# Group by 'question_id'
for question_id, group in df.groupby('question_id'):
# Sort by 'time'
group = group.sort_values('time')
# Find times when 'troll_closed' occurred
troll_closed_times = group[group['event_type'] == 'troll_closed']['time']
if not troll_closed_times.empty:
# Get the last 'troll_closed' time
last_troll_closed_time = troll_closed_times.max()
# Check if there is any 'reply' event after 'troll_closed'
replies_after_troll = group[(group['event_type'] == 'reply') & (group['time'] > last_troll_closed_time)]
if not replies_after_troll.empty:
ticket_count += 1
print("Number of tickets with replies after 'troll_closed':", ticket_count)
Question 4: Analysis of Ticket Tags
Objective: Count the number of tickets per tag, considering only the last tag in each ticket where event_subtype starts with 'tag_'. Provide the most popular tag.
Solution:
python
# Filter events where 'event_subtype' starts with 'tag_'
df_tags = df[df['event_subtype'].str.startswith('tag_')]
# For each 'question_id', get the last tag event
df_tags_last = df_tags.sort_values('time').groupby('question_id').tail(1)
# Count the number of tickets per tag
tag_counts = df_tags_last['event_subtype'].value_counts()
# Get the most popular tag
most_popular_tag = tag_counts.idxmax()
print("The most popular tag is:", most_popular_tag)
Question 5: Tag Most Frequently Set by Agents
Objective: Find the tag (event_subtype) that agents most frequently set manually (event_type = 'tag_set_manually').
Solution:
python
# Filter events where 'event_type' is 'tag_set_manually'
df_agent_tags = df[df['event_type'] == 'tag_set_manually']
# Count the frequency of each tag
agent_tag_counts = df_agent_tags['event_subtype'].value_counts()
# Get the most frequently set tag
most_frequent_agent_tag = agent_tag_counts.idxmax()
print("The tag most frequently set by agents is:", most_frequent_agent_tag)
Question 6: Change of Ticket Category with Status 0
Objective: Find the question_id of the ticket where there is an event event_type = 'set_category' with status = 0 at the time of the event.
Solution:
python
# Filter events where 'event_type' is 'set_category' and 'status' == 0
df_set_category_status_0 = df[(df['event_type'] == 'set_category') & (df['status'] == 0)]
# Get the unique 'question_id's
question_ids = df_set_category_status_0['question_id'].unique()
print("Question IDs with 'set_category' event and status 0:", question_ids)
Question 7: Calculation of UWT (User Waiting Time)
Objective: Calculate the average time a user waits for an agent's response, excluding deleted messages. Provide the average time in seconds with accuracy to hundredths.
Solution:
python
# Identify deleted replies by collecting 'reply_id's from 'delete_reply' events
deleted_reply_ids = df[df['event_type'] == 'delete_reply']['reply_id'].unique()
# Exclude deleted replies
df_no_deleted = df[~df['reply_id'].isin(deleted_reply_ids)]
# Function to calculate waiting times per ticket
def calculate_uwt(group):
group = group.sort_values('time')
waiting_times = []
waiting_for_response = False
t_user_question = None
for _, row in group.iterrows():
if row['event_type'] == 'reply':
if not waiting_for_response:
t_user_question = row['time']
waiting_for_response = True
elif row['event_type'] == 'agent_reply' and waiting_for_response:
t_agent_response = row['time']
waiting_time = (t_agent_response - t_user_question).total_seconds()
waiting_times.append(waiting_time)
waiting_for_response = False
return waiting_times
# Calculate UWT for all tickets
uwt_list = []
for question_id, group in df_no_deleted.groupby('question_id'):
uwt_list.extend(calculate_uwt(group))
# Calculate average waiting time
average_uwt = np.mean(uwt_list)
print(f"Average User Waiting Time (UWT): {average_uwt:.2f} seconds")
Question 8: Calculation of SL (Service Level)
Objective: Calculate the percentage of responses given within 15 minutes. Provide the SL value with accuracy to hundredths.
Solution:
python
# Total number of chains
total_chains = len(uwt_list)
# Number of chains with UWT ≤ 15 minutes (900 seconds)
chains_within_15min = sum(1 for uwt in uwt_list if uwt <= 900)
# Calculate Service Level
service_level = (chains_within_15min / total_chains) * 100
print(f"Service Level (SL): {service_level:.2f}%")
Question 9: Determining the Speed of Response of Employees
Objective: Determine which user_type group of employees gives the fastest responses to user questions.
Solution:
python
# Exclude deleted replies
df_no_deleted = df[~df['reply_id'].isin(deleted_reply_ids)]
# Initialize a DataFrame to collect response times and agent user types
response_times = []
for question_id, group in df_no_deleted.groupby('question_id'):
group = group.sort_values('time')
waiting_for_response = False
t_user_question = None
for _, row in group.iterrows():
if row['event_type'] == 'reply':
if not waiting_for_response:
t_user_question = row['time']
waiting_for_response = True
elif row['event_type'] == 'agent_reply' and waiting_for_response:
t_agent_response = row['time']
waiting_time = (t_agent_response - t_user_question).total_seconds()
agent_user_type = row['user_type']
response_times.append({'user_type': agent_user_type, 'waiting_time': waiting_time})
waiting_for_response = False
# Create a DataFrame from the response times
df_response_times = pd.DataFrame(response_times)
# Calculate average waiting time per 'user_type'
avg_response_time_by_user_type = df_response_times.groupby('user_type')['waiting_time'].mean()
# Find the 'user_type' with the smallest average response time
fastest_user_type = avg_response_time_by_user_type.idxmin()
print(f"The fastest responding user_type is: {fastest_user_type}")
Question 10: Time Until Ticket Closure
Objective: Calculate the average time from the last action in the ticket to its closure by timeout (event_type = 'closed_by_time'), excluding actions after closure.
Solution:
python
# Initialize a list to collect time differences
time_differences = []
for question_id, group in df.groupby('question_id'):
# Check if the ticket has 'closed_by_time' events
closed_by_time_events = group[group['event_type'] == 'closed_by_time']
if not closed_by_time_events.empty:
# Get the last 'closed_by_time' event
last_closed_time = closed_by_time_events['time'].max()
# Exclude actions after closure
actions_before_close = group[group['time'] < last_closed_time]
if not actions_before_close.empty:
last_action_time = actions_before_close['time'].max()
# Calculate time difference in days
time_diff = (last_closed_time - last_action_time).total_seconds() / (24 * 3600)
time_differences.append(time_diff)
# Calculate average time difference
average_time_difference = np.mean(time_differences)
print(f"Average time until ticket closure: {average_time_difference:.2f} days")
Question 11: Time Between Agent Assignment and Unassignment
Objective: Calculate the average time from agent assignment (event_type = 'set_agent') to agent unassignment (event_type = 'drop_agent'), excluding resets initiated by users.
Solution:
python
# Initialize a list to collect time differences
assignment_times = []
for question_id, group in df.groupby('question_id'):
group = group.sort_values('time')
assignment_time = None
for i, row in group.iterrows():
if row['event_type'] == 'set_agent':
assignment_time = row['time']
elif row['event_type'] == 'drop_agent' and assignment_time:
# Check if the 'drop_agent' was not initiated by user
if row['user_type'] != 'user': # Assuming 'user_type' indicates who initiated the event
drop_time = row['time']
time_diff = (drop_time - assignment_time).total_seconds()
assignment_times.append(time_diff)
assignment_time = None # Reset assignment time
else:
continue # Ignore drops initiated by users
average_assignment_time = np.mean(assignment_times)
print(f"Average time between assignment and unassignment: {average_assignment_time:.2f} seconds")
Note: For these solutions, it's essential to adjust the condition checks based on the actual possible values in fields such as 'user_type' and 'agent_role', according to the dataset's specifics.
Please ensure that the field names and logic correspond precisely with the data in SQL_data.xlsx. The provided code offers a framework and might require slight modifications to run successfully with your dataset.