تحميل مجموعة بيانات المبيعات وتدقيقها
استورد ملف CSV لسجلات الطلبات، ودقّق الأنواع dtypes والقيم المفقودة، وأصلح تحليل التواريخ وشذوذ الكميات السالبة.
تحميل مجموعة بيانات المبيعات وتدقيقها درس مجاني في Pandas & NumPy Academy على CoddyKit. هذا هو الدرس 1 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Pandas & NumPy Academy، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Pandas & NumPy Academy 4 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
Introducing the Sales Dataset
A typical sales dataset contains columns like order_id, order_date, customer_id, product, category, quantity, unit_price, and region. Before any analysis you must load this file and take a first look at its structure. The goal of this first step is to understand what data you have before writing a single formula.
import pandas as pd
df = pd.read_csv('sales.csv')
print(df.shape) # (rows, columns)
print(df.head())Checking Shape and Column Names
After loading, immediately check df.shape to know the dataset dimensions and df.columns to see all column names. This confirms the file loaded correctly and shows whether any column names have unexpected spaces or capitalisation that need cleaning. A mismatch in expected column count is an early warning sign of a corrupted file.
print('Rows, Cols:', df.shape)
print('Columns:', df.columns.tolist())
print('Index:', df.index[:5].tolist())Inspecting Data Types with dtypes
Use df.dtypes or df.info() to see the inferred data type of every column. Common problems include date columns loaded as object (string) and numeric columns loaded as object because of stray commas or currency symbols. Catching dtype issues early prevents silent errors in arithmetic later.
print(df.dtypes)
# More detail including non-null counts
df.info()Counting Missing Values
Run df.isna().sum() to count NaN values per column. Convert to a percentage with df.isna().mean() * 100 to see what fraction of each column is missing. Columns with more than 30–40 % missing usually need a decision: drop the column, impute, or flag as a separate indicator variable.
missing = df.isna().sum()
missing_pct = df.isna().mean() * 100
print(pd.DataFrame({'count': missing, 'pct': missing_pct}))Detecting Duplicate Rows
Duplicate order records inflate revenue totals and distort any per-customer analysis. Use df.duplicated().sum() to count exact duplicates and df.duplicated(subset=['order_id']).sum() to check for repeated order IDs, which should be unique. Identifying duplicates at load time saves hours of debugging later.
print('Exact duplicates:', df.duplicated().sum())
print('Duplicate order_ids:', df.duplicated(subset=['order_id']).sum())
# Preview the duplicated rows
print(df[df.duplicated(subset=['order_id'], keep=False)].head())Fixing Date Column Parsing
A date column loaded as object must be converted with pd.to_datetime() so you can do date arithmetic. Pass format='%Y-%m-%d' if you know the format, or use infer_datetime_format=True for mixed formats. After conversion, extract year and month with the .dt accessor for time-based grouping.
df['order_date'] = pd.to_datetime(df['order_date'], format='%Y-%m-%d')
df['year'] = df['order_date'].dt.year
df['month'] = df['order_date'].dt.month
print(df[['order_date', 'year', 'month']].head())Spotting Negative Quantities
Negative quantity values typically represent returns or data entry errors. Use boolean indexing to find them: df[df['quantity'] < 0]. Decide whether to treat them as legitimate returns (keep with a flag) or as errors (drop or correct). Always document your decision so the pipeline is reproducible.
negatives = df[df['quantity'] < 0]
print(f'Negative quantity rows: {len(negatives)}')
print(negatives.head())
# Flag returns separately
df['is_return'] = df['quantity'] < 0Checking Numeric Column Ranges
Use df.describe() to see the min, max, mean, and quartiles of every numeric column. A unit_price with a minimum of zero or a negative value is suspicious. A quantity maximum far above any reasonable order size might be a data entry error. Sanity-checking ranges is a fast way to spot anomalies.
print(df[['quantity', 'unit_price']].describe())
# Any price exactly 0?
print('Zero price rows:', (df['unit_price'] == 0).sum())Auditing Categorical Columns
For columns like region and category, use df['region'].value_counts() to see all unique values and their frequencies. Look for typos, inconsistent capitalisation (e.g. 'north' vs 'North'), or unexpected values that indicate upstream data issues. Standardise them before any groupby operation.
print(df['region'].value_counts())
print(df['category'].value_counts())
# Normalise capitalisation
df['region'] = df['region'].str.strip().str.title()Creating an Audit Summary
A structured audit summary DataFrame helps communicate data quality issues to stakeholders. Build one by collecting metrics like row count, column count, missing counts, and duplicate counts into a dictionary and converting it to a DataFrame. This summary becomes the first section of your analysis report and justifies every cleaning step you take.
audit = {
'rows': len(df),
'columns': len(df.columns),
'missing_cells': df.isna().sum().sum(),
'duplicate_rows': df.duplicated().sum(),
'date_range_start': df['order_date'].min(),
'date_range_end': df['order_date'].max()
}
for k, v in audit.items():
print(f'{k}: {v}')Saving a Clean Snapshot
After the initial audit and basic fixes (dtype corrections, duplicate removal, flag columns), save a clean snapshot so downstream steps always start from a consistent baseline. Use df.to_csv('sales_clean.csv', index=False) or, for faster reloading, df.to_parquet('sales_clean.parquet'). Parquet preserves dtypes including datetime, which CSV does not.
# Drop exact duplicates before saving
df = df.drop_duplicates(subset=['order_id'], keep='first')
# Save clean snapshot
df.to_parquet('sales_clean.parquet', index=False)
print('Saved', len(df), 'rows to sales_clean.parquet')Quick Check
Test your understanding of Data Analysis concepts from this lesson.
Lesson Recap
In this lesson you learned: loading a CSV and checking shape/columns, auditing dtypes, missing values, duplicates, and negative quantities, and saving a clean snapshot for downstream steps. Next up we explore revenue calculations and feature engineering on the clean dataset.
الأسئلة الشائعة
هل درس «تحميل مجموعة بيانات المبيعات وتدقيقها» مجاني؟
نعم — نص درس «تحميل مجموعة بيانات المبيعات وتدقيقها» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Pandas & NumPy Academy، انتقل إلى CoddyKit PRO. تتضمن دورة Pandas & NumPy Academy 4 دروس في المجموع.
ماذا ستتعلم في «تحميل مجموعة بيانات المبيعات وتدقيقها»؟
استورد ملف CSV لسجلات الطلبات، ودقّق الأنواع dtypes والقيم المفقودة، وأصلح تحليل التواريخ وشذوذ الكميات السالبة. تتمرن على Pandas & NumPy Academy مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ Pandas & NumPy Academy؟
لا تُشترط خبرة سابقة. Pandas & NumPy Academy على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 1 من أصل 4.
كم من الوقت يستغرق درس «تحميل مجموعة بيانات المبيعات وتدقيقها»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس Pandas & NumPy Academy هذا؟
نعم. كل درس في Pandas & NumPy Academy يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- تحميل مجموعة بيانات المبيعات وتدقيقها
- حساب الإيرادات وهندسة الميزات
- تحليل GroupBy حسب المنطقة والفئة
- تصور الاتجاه الشهري