Cong-Truong-202 / BIU-DATA

0 stars 0 forks source link

Detailed inventory analysis across categories and locations #7

Open Cong-Truong-202 opened 3 weeks ago

Cong-Truong-202 commented 3 weeks ago

import pandas as pd import matplotlib.pyplot as plt import numpy as np

Đọc dữ liệu từ các file CSV

customers_df = pd.read_csv("customers.csv") orders_df = pd.read_csv("orders.csv")

Kiểm tra kích thước của DataFrame chứa dữ liệu khách hàng

print(customers_df.shape)

Kiểm tra các cột trong DataFrame chứa dữ liệu đơn hàng

print(orders_df.columns.to_list())

Kiểm tra các giá trị thiếu trong DataFrame chứa dữ liệu khách hàng

print(customers_df.isnull().sum())

Xóa các cột không cần thiết hoặc có vấn đề trong DataFrame khách hàng

customers_df.drop('addressLine2', axis=1, inplace=True) # Xóa cột addressLine2 customers_df.drop('state', axis=1, inplace=True) # Xóa cột state customers_df.drop('salesRepEmployeeNumber', axis=1, inplace=True) # Xóa cột salesRepEmployeeNumber

Kiểm tra kích thước của DataFrame khách hàng sau khi xóa các cột

print(customers_df.shape)

Kiểm tra các giá trị thiếu trong DataFrame chứa dữ liệu đơn hàng

print(orders_df.isnull().sum())

Xóa các hàng có giá trị 'shippedDate' thiếu

orders_df.dropna(subset=["shippedDate"], inplace=True)

Xóa cột 'comments' trong DataFrame đơn hàng

orders_df.drop('comments', axis=1, inplace=True)

Kiểm tra kích thước của DataFrame đơn hàng sau khi xóa hàng và cột

print(orders_df.shape)

Chuyển đổi các cột ngày tháng sang định dạng datetime để dễ dàng xử lý

orders_df['requiredDate'] = pd.to_datetime(orders_df['requiredDate']) orders_df['orderDate'] = pd.to_datetime(orders_df['orderDate']) orders_df['shippedDate'] = pd.to_datetime(orders_df['shippedDate'])

Kết hợp hai DataFrame khách hàng và đơn hàng dựa trên 'customerNumber'

df = customers_df.merge(orders_df, on="customerNumber")

Nhóm dữ liệu theo 'country' và đếm số lượng đơn hàng

grouped_df = df.groupby("country")["orderNumber"].count().reset_index()

Nhóm dữ liệu theo 'city' và đếm số lượng đơn hàng

grouped2_df = df.groupby("city")["orderNumber"].count().reset_index()

Hiển thị kết quả nhóm dữ liệu

print(grouped_df) print("---------------------------------------") print(grouped2_df)

Chọn loại biểu đồ để vẽ

chart_type = "bar"

Vẽ biểu đồ cột tổng đơn hàng theo quốc gia

if chart_type == "bar": plt.figure(figsize=(10, 6)) plt.bar(grouped_df["country"], grouped_df["orderNumber"]) plt.xlabel("Quốc gia") plt.ylabel("Tổng đơn hàng") plt.title("Tổng đơn hàng theo Quốc gia") plt.xticks(rotation=45, ha="right") plt.tight_layout() plt.show()

Vẽ biểu đồ cột tổng đơn hàng theo thành phố

if chart_type == "bar": plt.figure(figsize=(20, 6)) plt.bar(grouped2_df["city"], grouped2_df["orderNumber"]) plt.xlabel("Thành phố") plt.ylabel("Tổng đơn hàng") plt.title("Tổng đơn hàng theo Thành phố") plt.xticks(rotation=45, ha="right") plt.tight_layout() plt.show()

Lọc dữ liệu cho thành phố Madrid

selected_df = df[df["city"] == "Madrid"]

Sắp xếp các thành phố theo số lượng đơn hàng giảm dần

grouped2_df = grouped2_df.sort_values(by="orderNumber", ascending=False)

Lấy 10 thành phố có số lượng đơn hàng cao nhất

top_10_cities = grouped2_df.head(10)

Hiển thị 10 thành phố có số lượng đơn hàng cao nhất

print(top_10_cities)

Vẽ biểu đồ cột cho 10 thành phố có số lượng đơn hàng cao nhất

plt.figure(figsize=(8, 5)) plt.bar(top_10_cities["city"], top_10_cities["orderNumber"], color='skyblue') plt.xlabel("Thành phố") plt.ylabel("Tổng số đơn hàng") plt.title("Top 10 Thành phố có Tổng số Đơn hàng Cao nhất") plt.xticks(rotation=45, ha="right") plt.tight_layout() plt.show()

Tính toán thời gian giao hàng cho từng đơn hàng

df['thoi_gian_giao_hang'] = df['shippedDate'] - df['orderDate'] df['thoi_gian_giao_hang'] = df['thoi_gian_giao_hang'].dt.days

Nhóm dữ liệu theo 'country' và tính toán thời gian giao hàng trung bình

df_grouped = df.groupby("country")['thoi_gian_giao_hang'].mean()

Sắp xếp thời gian giao hàng trung bình theo thứ tự giảm dần

df_grouped = df_grouped.sort_values(ascending=False)

Nhóm dữ liệu theo 'country' và tính toán thời gian giao hàng trung bình và số lượng đơn hàng

df_grouped_DS = df.groupby('country')['thoi_gian_giao_hang'].agg(['mean', 'count'])

Sắp xếp theo thời gian giao hàng trung bình giảm dần

df_grouped_DSSX = df_grouped_DS.sort_values(by="mean", ascending=False)

Xác định quốc gia có thời gian giao hàng ngắn nhất

khu_vuc_ngan_nhat = df_grouped.idxmin() thoi_gian_ngan_nhat = df_grouped.min()

Hiển thị kết quả

print(f"Quốc gia có thời gian giao hàng ngắn nhất là: {khu_vuc_ngan_nhat}") print(f"Thời gian giao hàng trung bình tại quốc gia này là: {thoi_gian_ngan_nhat} ngày") print(f"--------------------------------------------------") print(f"Danh sách thời gian giao hàng trung bình theo từng quốc gia:\n {df_grouped_DS}") print(f"--------------------------------------------------") print(f"Danh sách thời gian giao hàng giảm dần:\n {df_grouped_DSSX}") print(f"--------------------------------------------------")

Vẽ biểu đồ cột cho thời gian giao hàng trung bình theo quốc gia

plt.figure(figsize=(10, 6)) df_grouped.plot(kind='bar', color='skyblue') plt.xlabel('Quốc gia') plt.ylabel('Thời gian giao hàng trung bình (ngày)') plt.title('Thời gian giao hàng trung bình theo Quốc gia') plt.xticks(rotation=45) plt.tight_layout() plt.show()

Hiển thị 10 quốc gia có thời gian giao hàng ngắn nhất

top_10_ngan_nhat = df_grouped_DS.nsmallest(10, "mean").reset_index() print("Top 10 quốc gia có thời gian giao hàng ngắn nhất:") print(top_10_ngan_nhat)

Hiển thị 10 quốc gia có thời gian giao hàng dài nhất

top_10_dai_nhat = df_grouped_DS.nlargest(10, "mean").reset_index() print("\nTop 10 quốc gia có thời gian giao hàng dài nhất:") print(top_10_dai_nhat)

Vẽ biểu đồ ngang cho 10 quốc gia có thời gian giao hàng ngắn nhất

plt.figure(figsize=(7, 3)) plt.barh(top_10_ngan_nhat["country"], top_10_ngan_nhat["mean"], color='orange') plt.xlabel('Thời gian giao hàng trung bình (ngày)') plt.ylabel('Quốc gia') plt.title('Top 10 Quốc gia có Thời gian Giao hàng Ngắn nhất') plt.gca().invert_yaxis() plt.grid(axis='x', linestyle='--', alpha=0.6) plt.tight_layout() plt.show()

Vẽ biểu đồ ngang cho 10 quốc gia có thời gian giao hàng dài nhất

plt.figure(figsize=(7, 3)) plt.barh(top_10_dai_nhat["country"], top_10_dai_nhat["mean"], color='skyblue') plt.xlabel('Thời gian giao hàng trung bình (ngày)') plt.ylabel('Quốc gia') plt.title('Top 10 Quốc gia có Thời gian Giao hàng Dài nhất') plt.gca().invert_yaxis() plt.grid(axis='x', linestyle='--', alpha=0.6) plt.tight_layout() plt.show()

Tính toán trung bình thời gian giao hàng theo quốc gia và số lượng đơn hàng

avg_delivery_time_by_region = df.groupby("country")["thoi_gian_giao_hang"].agg(['mean', 'count']).reset_index()

Sắp xếp theo thời gian giao hàng trung bình giảm dần

df_grouped_DSSX = avg_delivery_time_by_region.sort_values(by="mean", ascending=False)

Hiển thị danh sách thời gian giao hàng trung bình của từng quốc gia

print("Danh sách thời gian giao hàng trung bình của từng quốc gia:") print(df_grouped_DSSX)

Vẽ biểu đồ thanh chồng cho thời gian giao hàng trung bình và số lượng đơn hàng theo quốc gia

fig, ax = plt.subplots() ax.bar(df_grouped_DSSX["country"], df_grouped_DSSX["mean"], color="skyblue", label="Thời gian giao hàng trung bình") ax.bar(df_grouped_DSSX["country"], df_grouped_DSSX["count"], color="orange", bottom=df_grouped_DSSX["mean"], label="Số lượng đơn hàng") ax.set_xlabel("Quốc gia") ax.set_ylabel("Giá trị") ax.set_title("Thời gian giao hàng trung bình và Số lượng đơn hàng theo Quốc gia") ax.legend() plt.xticks(rotation=45, ha="right") plt.tight_layout() plt.show()