0% found this document useful (0 votes)
5 views9 pages

Codes

The document outlines a series of Python code snippets that demonstrate data manipulation and visualization using pandas and matplotlib. It includes reading CSV files, cleaning data, converting data types, and generating various plots to analyze service quality metrics. The final output is a comprehensive report summarizing key findings, trends, and recommendations for improving service quality, formatted as a PDF document.

Uploaded by

vaneeta
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views9 pages

Codes

The document outlines a series of Python code snippets that demonstrate data manipulation and visualization using pandas and matplotlib. It includes reading CSV files, cleaning data, converting data types, and generating various plots to analyze service quality metrics. The final output is a comprehensive report summarizing key findings, trends, and recommendations for improving service quality, formatted as a PDF document.

Uploaded by

vaneeta
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

import pandas as pd

2
3# Read the CSV file into a DataFrame
4df = pd.read_csv('Waiter_Hourly_Schedule.csv')
5
6# Display the first 5 rows
7print([Link]())
8
9# Print the column names and their data types
[Link]()

# Remove leading and trailing spaces from column names


[Link] = [Link]()
4
5# Print the updated column names
6print([Link])

660bf8270a0762ed0243f7ad

660bf8270a0762ed0243f7ad

66099cf7253038dfe2ec41fb
import [Link] as plt
3
4# Convert 'MOIC' and 'Deal Level IRR' columns to numeric
5df['MOIC'] = pd.to_numeric(df['MOIC'], errors='coerce')
6df['Deal Level IRR'] = pd.to_numeric(df['Deal Level IRR'].[Link]('%', repl='').[Link](), errors='coerce') / 100
7
8# Create the scatter plot
[Link](figsize=(12, 8))
10scatter = [Link](df['Asset Class'], df['Investment Type'], s=df['MOIC'] * 100, c=df['Deal Level IRR'], cmap='coolwarm')
11
12# Customize plot appearance
[Link]('Asset Class', fontsize=12)
[Link]('Investment Type', fontsize=12)
[Link]('Bubble Chart: Asset Class vs. Investment Type', fontsize=14)
[Link](rotation=45, ha='right')
[Link](scatter, label='Deal Level IRR')
18
19# Show the plot
20plt.tight_layout()
[Link]()

import [Link] as plt

# Convert 'MOIC' and 'Deal Level IRR' columns to numeric


df['MOIC'] = pd.to_numeric(df['MOIC'], errors='coerce')
df['Deal Level IRR'] = pd.to_numeric(
df['Deal Level IRR'].[Link]('%').[Link](',', repl='.', regex=True),
errors='coerce',
)

# Create the bubble chart


[Link](
x=df['Asset Class'],
y=df['Investment Type'],
s=df['MOIC'] * 50, # Scale bubble size for better visualization
c=df['Deal Level IRR'],
cmap='viridis', # Choose a colormap
alpha=0.7, # Add transparency for overlapping points
)

# Customize the plot


[Link]('Asset Class')
[Link]('Investment Type')
[Link]('Investment Performance by Asset Class and Type')
[Link](label='Deal Level IRR')
[Link](rotation=45)
plt.tight_layout()
# Show the plot
[Link]()

Then plot the chart:

1. Import [Link] as plt.


2. Use [Link] to create the bubble chart with 'Asset Class' on the x-axis, 'Investment
Type' on the y-axis, bubble size based on (MOIC * 100) and color based on (Deal
Level IRR * 100).
3. Adjust the plot aesthetics for better readability and presentation.
4. Display the plot.

02/04/2024

660b0b10e0984713d97b9e79

660b0b11e0984713d97b9eb2

I can see that dataframe columns are not correct so I will assign a new row as the columns of the dataframe and then I will skip the irrelevant rows.

Coder Instructions:

1. Assign the first row as a header or new columns of the dataframe using [Link][].

2. Modify the dataframe by skipping the irrelevant row of the dataframe.

3. Print the list of the new columns of the dataframe.

4. Show the columns and type using info().

# Assign the first row as a header

[Link] = [Link][2]

# Skip the first 3 rows in the DataFrame

df = [Link][2:]

#df = [Link](index=0).reset_index(drop=True)

df.reset_index(drop=True, inplace=True)
# Print the list of the new columns

print([Link].to_list())

# Show the columns and their data types

print([Link]())

import pandas as pd
import numpy as np

pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)

# Read the CSV file into a DataFrame


df = pd.read_csv('messy_BLACK RAINBOW Data [Link]')

[Link] = [Link]()

for col in ['MONTH', 'YEAR']:


# Remove quotation marks and non-numeric characters before converting to numeric.
df[col] = pd.to_numeric(df[col].[Link]('"').[Link]('[^\d\-+]', repl='', regex=True), errors='coerce')

# Replace infinite or missing values with a default value (0 in this case).


df['MONTH'] = df['MONTH'].replace([[Link], -[Link], [Link]], 0)
df['YEAR'] = df['YEAR'].replace([[Link], -[Link], [Link]], 0)

# Convert 'YEAR' and 'MONTH' columns to integers.


df['MONTH'] = df['MONTH'].astype(int)
df['YEAR'] = df['YEAR'].astype(int)

df['DATE'] = pd.to_datetime(
df['YEAR'].astype(str).fillna('') + '-' + df['MONTH'].astype(str).fillna('')
)

# print(df[['MONTH', 'YEAR', 'DATE']].head().to_markdown(index=False))

for col in ['MONTH', 'YEAR']:

df[col] = df[col].astype(str).[Link]('"', '')

for col in ['MONTH', 'YEAR']:

df[col] = pd.to_numeric(df[col]).fillna(0).astype(int)

df['DATE'] = pd.to_datetime(df['YEAR'].astype(str) + '-' + df['MONTH'].astype(str),


format='%Y-%m')
print(df[['DATE', 'MONTH', 'YEAR']].head(3).to_markdown(index=False, numalign="left",
stralign="left"))

09/04/2024 - 6612f292fb8b2c5fb8db76ae- earning issue


import [Link] as plt

# Convert `Clients` and `Visits` columns to string


df["Clients"] = df["Clients"].astype(str)
df["Visits"] = df["Visits"].astype(str)

# Remove '-' from `Clients` column and unwanted characters from both columns
df["Clients"] = df["Clients"].[Link]("[^\d+\.]", "", regex=True)
df["Visits"] = df["Visits"].[Link]("[^\d+\.]", "", regex=True)

# Convert columns to numeric with coercion; invalid parsing will result in NaN
df["Clients"] = pd.to_numeric(df["Clients"], errors="coerce").fillna(0)
df["Visits"] = pd.to_numeric(df["Visits"], errors="coerce").fillna(0)

#correlations = [Link]('Day').agg({'Clients': lambda x: [Link](df['Visits'])}).reset_index()


df_agg = (
[Link](['Day'])
.corr()
.loc[:, 'Clients', 'Visits']
.reset_index()
)

# Group by day
df_agg = df_agg.groupby('Day').agg({'Visits': 'first'})
df_agg['size'] = [Link]('Day')['Visits'].transform('sum')

# Create scatterplot
[Link](figsize=(8, 6))
[Link](
df["Clients"], df["Visits"], s=75, alpha=0.5, c=[Link], cmap="viridis"
)

# Label points with day numbers


for i, row in df.reset_index().iterrows():
[Link](
row["Day"],
(row["Clients"], row["Visits"]),
xytext=(5, 5),
textcoords="offset pixels",
)

# Plot styling
[Link]("Clients", fontsize=12)
[Link]("Visits", fontsize=12)
[Link]("Correlation between Clients and Visits", fontsize=14)
[Link](label="Day Number")
[Link](0, df["Clients"].max() + 5)
[Link](0, df["Visits"].max() + 10)
[Link](True)

# Show plot
plt.tight_layout()
[Link]()
"Generate a comprehensive report summarizing key findings, trends, and recommendations for improving service quality, formatted as a PDF document.",
and the dataset, messy_Ticket ratings .xlsx, please rate each of the following model responses, then choose the better one and improve it if possible.

import pandas as pd

# Read the CSV file into a DataFrame


df = pd.read_csv('messy_Ticket ratings .xlsx - [Link]')

# Display the first 5 rows


print([Link]())

# Get information about the columns

print([Link]())

# Remove invalid characters and convert to datetime


# YYYY-MM-DD HH:MM:[Link] -> YYYY-MM-DD
df['Date'] = pd.to_datetime(
df['Date'].astype('str').[Link](0, 10), format='%Y-%m-%d'
)

# Verify the conversion

print(df['Date'].dtype)

# Get and print column names.

print([Link]())

# Remove invalid characters and convert to datetime


# YYYY-MM-DD HH:MM:[Link] -> YYYY-MM-DD
df['Date '] = pd.to_datetime(
df['Date '].astype('str').[Link](0, 10), format='%Y-%m-%d'
)

# Verify the conversion

print(df['Date '].dtype)

# Filter rows with invalid date format


invalid_dates = df[~df['Date '].astype(str).[Link](r'^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$')]

# Get unique non-numeric date values


unique_values = invalid_dates['Date '].unique()

# Print up to 20 unique values or all if there are less


if len(unique_values) > 20:
print(unique_values[:20])
else:

print(unique_values)

import pandas as pd

# Filter rows with invalid date format and length


df = df[
df['Date '].astype(str).[Link]().str[0].[Link]() >= 10
]

# Convert 'DD/MM/YYYY' to 'YYYY-MM-DD' while keeping 'YYYY-MM-DD' unchanged


def convert_date_format(date_str):
if len(date_str.split('/')) == 3: # 'DD/MM/YYYY' format
return '/'.join(reversed(date_str.split('/'))) # Reverse to 'YYYY-MM-DD'
else:
return date_str # Keep 'YYYY-MM-DD' format

df['Date '] = df['Date '].astype(str).[Link]().str[0].apply(convert_date_format)

# Convert to datetime and handle errors


df['Date '] = pd.to_datetime(df['Date '], errors='coerce')
# Remove rows with invalid dates after conversion
df = [Link](subset=['Date '])

print(df['Date '].head())

import [Link] as plt

# Subset of columns with new names


df_subset = df[['Date', 'Product_Rating', 'Service_Rating', 'Response', 'Handling', 'Closure', 'SLA_Compliance']]

# Convert columns to numeric


columns_to_convert = ['Product_Rating', 'Service_Rating', 'Response', 'Handling', 'Closure', 'SLA_Compliance']
for col in columns_to_convert:
df_subset[col] = pd.to_numeric(df_subset[col], errors='coerce')
df_subset[col] = df_subset[col].fillna(0)

# Group the data by 'Date' to calculate daily averages


grouped_data = df_subset.groupby('Date')[columns_to_convert].mean()

# Plot all the service quality rating trends


[Link](figsize=(10, 6))
for col in columns_to_convert:
[Link](grouped_data.index, grouped_data[col], label=col)

[Link]('Service Quality Trends')


[Link]('Date')
[Link]('Average Rating')
[Link]()

[Link]()

import datetime

current_date = [Link]()

report_text = f"""
Service Quality Report
Date: {current_date}

Report Summary

This report analyzes various service quality metrics for the period covered by the dataset (2022-01-02 to 2022-12-29). The analysis reveals the following trends and
insights:

* Product Rating, Service Rating, and Closure ratings have shown a mostly increasing trend over time.
* Response and Handling ratings saw a small fluctuation but remained near a 0 rating.
* SLA Compliance has fluctuated but remained above a rating of 0.5 for the later half of the year.

Recommendations

Based on the analysis, the following recommendations are made to improve service quality:

* Continue efforts to improve Product Rating, Service Rating, and Closure ratings, as they directly impact customer satisfaction.
* Investigate the causes of fluctuations in Response and Handling ratings, and identify opportunities for improvement.
* Ensure consistent adherence to SLA Compliance to maintain customer satisfaction.

Methodology

The analysis was conducted using Python and Pandas libraries. The dataset was cleaned and transformed to calculate average ratings for each metric on a daily basis.
The trends were visualized using a line plot.

Conclusion

The analysis provides insights into the service quality trends for the period under review. The recommendations presented can help guide efforts to further improve
service quality and customer satisfaction.

Additional Notes

The analysis may be refined by incorporating additional data, such as seasonality or external factors, to identify any correlations or patterns. Regular monitoring and
reporting of service quality metrics can help track progress and identify areas for further improvement.
"""

with open('Service Quality [Link]', 'w') as f:

[Link](report_text)

Instructions:
Coder Instructions:

1. Read "messy_Ticket ratings .xlsx - [Link]" into a Pandas Dataframe.

2. Display the first 5 rows of the DataFrame using the [Link]() method.

3. Get information about the columns in the DataFrame, including their data types, using the [Link]() method.

Coder Instructions:

1. Read "messy_Ticket ratings .xlsx - [Link]" into a Pandas Dataframe.

2. Display the first 5 rows of the DataFrame using the [Link]() method.

3. Get information about the columns in the DataFrame, including their data types, using the [Link]() method.

4. Output:

The Date column appears to be missing. I will print the column names to verify the correct column name.

Coder Instructions:

1. Print the column names.

Output:

The column that corresponds to Date is called Date in the dataframe. I can now proceed with
the date parsing as well as the data analysis.

1. I will standardize the date column to ensure consistency.


2. I'll calculate the average ratings for each service quality aspect by month and visualize
the trends using line plots.

Coder Instructions:

1. Remove the HH:MM:[Link] part from the Date (note the extra space in the column
name) column and convert it to datetime using to_datetime

Output:

It seems there's a ValueError while converting the column Date to datetime since "2022-0z8-
0" doesn't match the format. Since the Date column is not datetime, I will check the values
that don't match the format.

Coder Instructions:

1. Filter all rows of 'Date ' where the value does not match YYYY-MM-DD HH:MM:SS
2. If there are more than 20 unique non-numeric values, print 20 of them.
3. Otherwise, print all unique non-numeric values from the 'Date ' column.

Output:

There are several non-standard date formats in the data, such as '2022-06-02 00:00:'. Some
dates are in DD/MM/YYYY format, which I will standardize to YYYY-MM-DD to calculate
monthly average ratings for each service quality aspect and visualize trends with line plots.

Coder Instructions:
1. Split the Date column by a space ' ', take the first part, and remove any character
different than numbers, hyphen '-' and slash '/', and replace the values.
2. check the first part length is greater or equal than 10, if it is not, remove the row.
3. Convert all date values which are in 'DD/MM/YYYY' format to 'YYYY-MM-DD',
while keeping the already 'YYYY-MM-DD' format dates unchanged.
4. Convert the Date column to datetime using to_datetime
5. If any conversion fails, remove the row.

Output:

Now that the date column is standardized, I will proceed by calculating the average ratings
for each service quality aspect by month. I will then visualize the trends using line plots to
gain insights into how these ratings have evolved over time.

Coder Instructions:

Tidy the data:

1. Create a copy of the dataframe with a subset of columns: 'Date ', Product_Rating ',
'Service_Rating ', 'Response ', 'Handling ', 'Closure ', and 'SLA_Compliance ' (note the
space at the end).

Transform the data:

1. Convert the columns with object type to numeric.

Visualize the outputs:

1. Plot all the service quality rating trends in a line plot.

Output:

Based on the analysis, the service quality metrics show varying trends over time.

 Product Rating and Service Rating initially decline but show signs of improvement
in the latter half of the observed period.
 Response and Handling ratings are relatively low and show inconsistent trends.
 Closure ratings are consistently low, indicating a potential area for improvement.

Based on these insights, here are some recommendations to improve service quality:

1. Prioritize Closure improvements to enhance customer satisfaction.


2. Focus on consistent Response and Handling to provide better customer support.
3. Monitor Product and Service quality trends to ensure sustained improvement.

Coder Instructions:

Write the report, incorporating the findings, trends, and recommendations, and save it as a
PDF document titled 'Service Quality [Link]'. Format it according to professional
standards.

You might also like