Python Basics and Syntax
Python Basics and Syntax
Begin by understanding what Python is and how to run code. Python is a high-level, interpreted
programming language known for its readability and clear syntax 1 . It uses English-like keywords and
simple structure, making it beginner-friendly. Python code can be written in many environments: for
example, IDLE, which comes with Python by default, provides a simple interface for writing and running
code 2 ; and Google Colab is a free, cloud-hosted Jupyter Notebook service that requires no setup and
even offers free GPUs and TPUs for computation 3 . You might start with a simple “Hello, World!” program
to verify your setup:
• print is a built-in Python function that outputs data to the screen or console.
• The parentheses (...) enclose the argument passed to the function.
• "Hello, world!" is a string literal (text enclosed in quotes). In this case, it’s the message that
will be printed.
• The # symbol starts a comment which explains the code; comments are ignored when the
program runs.
Variables store data and can be created by simple assignment. For example:
• message is a variable name; variable names should be descriptive and follow naming rules
(letters, numbers, and underscores, not starting with a number).
• = assigns the string "Hello, world!" to the variable message .
• The second line calls print(message) , which outputs the contents of the message variable.
Python supports basic data types like integers ( 42 ), floats ( 3.14 ), strings ( "text" ), and booleans
( True / False ). You can perform arithmetic, use lists ( [ ] ), dictionaries ( { } ), and more. For example,
a list of numbers can be defined and summed:
numbers = [1, 2, 3, 4]
total = sum(numbers) # sum() adds all items in the list.
print(total) # Outputs: 10
1
• print(total) then displays the result (here, 10 ).
To switch from a local environment (like IDLE) to an online one like Colab, simply create a new notebook on
Google Colab and copy your code. Colab notebooks allow you to run Python code in cells and visualize
outputs inline. This is helpful for data science because you can combine code, outputs, and explanatory text
in one document.
• pandas – powerful for data manipulation and analysis (tables, CSV files) 4 .
• NumPy – for numerical operations on arrays and matrices.
• scikit-learn – machine learning library with algorithms and tools like OneHotEncoder ,
train_test_split , etc.
• Matplotlib and Seaborn – for creating visualizations (plots, charts) 4 5 .
Each library adds functionality: for example, pandas provides DataFrame objects for tabular data, and
[Link] has plotting functions like plot() and show() .
• Indentation is crucial in Python. Indents (spaces or tabs) define code blocks (loops, functions). A
common error is inconsistent indentation.
• Remember case-sensitivity: Variable and variable are different.
• Use print(type(var)) to check a variable’s type if you’re unsure.
• If a function or variable is not found, ensure you have the correct import statement, e.g., import
pandas as pd .
5. D. Imports a library
7. A. 2ndValue
8. B. my-var
9. C. my_var (Correct)
10. D. print
2
x = 5
y = 2
print(x * y)
12. A. 52
13. B. 7
14. C. 10 (Correct)
15. D. Error
References
Basic Python: its readable syntax and design philosophy 1 ; running code in IDLE 2 and Colab 3 .
Handling missing values: In pandas, the dropna() and fillna() methods are key. Use
[Link]() to remove rows with any missing values. As per pandas documentation: “The dropna()
method removes the rows that contain NULL values.” 6 . For example:
import pandas as pd
df = [Link]({
'A': [1, None, 3],
'B': [4, 5, None]
})
clean_df = [Link]()
print(clean_df)
• [Link]() returns a new DataFrame with only the rows that have no missing data in any
column. In this example, only row 0 would remain because rows 1 and 2 have None (missing)
values.
If you want to fill missing values instead of dropping, [Link](value) replaces NaN s with a given
value. Pandas notes that “fillna() replaces NA values with non-NA data.” 7 . For instance:
3
filled_df = [Link](0) # Replaces all missing values with 0.
print(filled_df)
• Now any None becomes 0 in the output. This keeps the shape of the DataFrame intact.
Use dropna() when missingness is minimal or likely random; use fillna() (with mean, median, or
constant) to retain rows. You can also forward-fill ( [Link]() ) or backward-fill ( [Link]() ) to
propagate values.
Removing duplicates: Duplicate records can bias analysis. Pandas provides drop_duplicates() to
remove duplicate rows. By default, “Return DataFrame with duplicate rows removed.” 8 . For example:
df2 = [Link]({
'Name': ['Alice', 'Bob', 'Alice', 'Charlie'],
'Score': [90, 80, 90, 85]
})
unique_df = df2.drop_duplicates()
print(unique_df)
• Only one of the identical 'Alice', 90 rows would be kept. You can specify subset columns or
keep first/last occurrence with parameters.
Additional cleaning steps: After fixing missing data and duplicates, common tasks include:
- Fixing data types: Ensure numeric columns are numeric ( df['age'] = df['age'].astype(int) ).
- Dealing with outliers: Identify values far from the norm and decide whether to keep or adjust them.
- Standardizing text: Lowercase strings, strip whitespace, correct typos.
Quality data cleaning prevents garbage-in-garbage-out and builds trust in your analysis.
7. A. Using drop_duplicates()
8. B. Using fillna() (Correct)
9. C. Using fill_values()
4
11. What is the effect of df2.drop_duplicates(subset=['Name']) ?
12. A. Removes all rows with duplicate names, keeping only unique names. (Correct)
13. B. Removes duplicate scores only.
14. C. Fills duplicate names with NaN.
15. D. Combines duplicates into one row.
References
Matplotlib Basics
• [Link](figsize=(6,4)) creates a blank canvas (Figure) to draw on, with specified size.
• [Link](x, y) draws a line plot with points (x[i], y[i]) . It accepts many parameters
(color, linestyle, etc.).
• [Link]/ylabel/title() add labels and a title to make the plot self-explanatory.
• [Link]() shows labels (set via label='Line' ) in the corner.
• [Link]() tells Python to display the plot. In Jupyter or Colab, it is often optional because cells
auto-render, but in scripts it’s needed.
You can also create scatter plots, histograms, bar charts, etc. For example:
5
[Link](['A', 'B', 'C'], [10, 5, 15])
[Link]('Bar Chart')
[Link]()
Matplotlib’s syntax can be procedural (as above) or object-oriented using Figure and Axes objects (for
more control). The example in the docs:
Matplotlib can output publication-quality figures and supports interactive features (zooming, panning) in
GUI backends.
Seaborn simplifies common statistical plots with pleasing styles. It integrates with pandas DataFrames
easily. First, import Seaborn (often alias sns ):
corr = [Link]()
[Link](corr, annot=True, square=True, cmap='coolwarm')
[Link]('Feature Correlation Heatmap')
[Link]()
6
Matplotlib and Seaborn together “make easy things easy and hard things possible” 5 when it comes to
plotting.
5. D. Bokeh
7. A. Enables 3D plots.
8. B. Sets a background style with white grid lines. (Correct)
9. C. Clears all existing plots.
12. A. [Link]()
13. B. [Link]() (Correct)
14. C. [Link]()
15. D. print(plt)
References
Machine learning models generally require numeric input. One-hot encoding converts a categorical
feature with k categories into k binary columns (each category has its own column) 9 . For example, if a
feature Color has values ['Red','Blue','Green'] , one-hot encoding creates three new features:
Color_Red , Color_Blue , Color_Green , with 1/0 indicating presence. In scikit-learn:
7
from [Link] import OneHotEncoder
encoder = OneHotEncoder(sparse=False)
X = encoder.fit_transform([['Red'], ['Blue'], ['Red']])
print(X)
• The order of columns corresponds to the sorted categories (e.g., ['Blue', 'Green', 'Red'] ).
One-hot encoding is essential for algorithms that cannot work directly with text labels 9 . Remember it can
create many new columns (if categories are many), which might be problematic (the “curse of
dimensionality”). Sometimes you can reduce columns by dropping one (using drop='first' ) to avoid
multicollinearity in linear models.
Label encoding (Ordinal encoding) is another approach: convert categories to integer labels. This is done
for target labels with LabelEncoder in scikit-learn. It assigns each class a number between 0 and n-1
10 . For example:
• Here, le.fit_transform learned that ‘ham’ and ‘spam’ map to some integer classes.
• LabelEncoder is for encoding the target label (often the y in supervised learning) 10 . It’s not
recommended for input features if the categories are nominal, because the numeric values might
imply an order. If categories have an inherent order, consider using ordinal encoding or mapping
manually.
Example of standardization:
8
from [Link] import StandardScaler
scaler = StandardScaler()
scaled_feats = scaler.fit_transform(df[['height', 'weight']])
• This is important for distance-based models (KNN, SVM) or methods that assume normal
distribution. It prevents features with large numeric ranges from dominating the model.
Sometimes combining or extracting information yields better predictors. For example, from the Titanic
dataset: create a new feature FamilySize as the sum of SibSp + Parch + 1 (siblings + parents +
self). Or extract titles from names (e.g., 'Mr', 'Mrs') using string methods or regex, as shown:
import re
def get_title(name):
match = [Link](' ([A-Za-z]+)\.', name)
return [Link](1) if match else ''
df['Title'] = df['Name'].apply(get_title)
• This code defines a function to extract a title (sequence of letters followed by a dot) from the
Name .
• [Link] finds the first match. group(1) returns the matched title.
• df['Name'].apply(get_title) applies this function to each row’s Name, creating a new
column Title .
Engineering features often requires domain knowledge. Always cross-validate that new features help your
model by testing performance.
9
11. How do you use StandardScaler in scikit-learn?
References
[Link]()
This outputs a table with count, mean, std, min, 25%, 50%, 75%, max for each numeric column
13 . For categorical columns, it shows count, unique, top, freq .
• Value counts: For categorical data, df['column'].value_counts() shows how many entries
per category. This quickly reveals class imbalances or dominant categories.
df[['Pclass','Survived']].groupby('Pclass').mean()
Groups data by passenger class and computes average survival rate. This might show, for example,
that 1st class had a higher average survival than 3rd class. The code groups rows by Pclass and
then takes the mean of Survived in each group.
• Correlations: Calculate [Link]() to see linear correlations between numeric features. Visualize
with [Link]([Link](), annot=True) . Highly correlated features might be redundant.
10
• Visual EDA: Plot histograms ( [Link]() ), box plots ( [Link]() ), scatter plots
( [Link]() ), etc. For example, a histogram of ages shows age distribution; a boxplot by
category shows medians and outliers.
EDA is iterative: generate plots and stats, then investigate any interesting or unexpected results. Always
document insights: e.g., “The majority of students came from São Paulo (74%), and over 90% of students
scored at least 5.0 on the CSAT survey,” if such pattern appears. Good EDA reveals data quality issues and
guides feature engineering.
Quiz: EDA
12. A. scikit-learn
13. B. pandas (no built-in heatmap)
14. C. seaborn (Correct)
15. D. NumPy
References
Case Studies
Working through real datasets cements understanding. We include three case studies: Titanic Survival,
Student Dropout, and EasyShop CSAT. Each demonstrates a complete workflow: data loading, cleaning,
EDA, feature engineering, modeling, and evaluation.
11
Titanic Survival (Kaggle)
Dataset: Contains passenger info (age, sex, class, etc.) and whether each person survived the Titanic
disaster. The goal is to predict survival.
Example steps:
- Load data with pd.read_csv('[Link]') .
- Data cleaning: fill missing ages (e.g., df['Age'].fillna(df['Age'].median(), inplace=True) ),
encode Sex ( df['Sex'].map({'male':0,'female':1}) ), and Embarked (e.g., map 'S','C','Q'
to 0,1,2).
- Feature engineering: Extract titles from names (e.g., use regex as in [44] ), create
FamilySize = SibSp + Parch + 1 .
- EDA: Use groupby to check survival rates by class, sex, etc. For instance, one may find that women and
children in higher classes had much higher survival rates.
- Modeling: Train a classifier (e.g., logistic regression) on features like Pclass, Sex, Age, Fare, Title, FamilySize.
- Evaluation: Assess accuracy, confusion matrix, ROC on a held-out test set.
Insight: Typically, female passengers and first-class passengers had higher survival rates. For example,
grouping by sex and averaging survival shows ~74% survival for women vs ~19% for men 14 . This aligns
with the “women and children first” policy. Titanic data is iconic for teaching EDA and feature engineering
(adding titles, handling cabin numbers, etc.).
Student Dropout
Dataset: Contains demographics, grades, and dropout indicators for students. The task is to predict if a
student will drop out.
Workflow:
- Clean data: handle missing test scores, attendance, etc.
- Convert categorical data (e.g., education level, gender) using encoding.
- Visualize distributions of grades, attendance and how they differ between dropouts vs persisters.
- Feature engineering might include: the number of failed courses, or change in grades over semesters.
- Split into train/test, train models like Random Forest.
- Evaluate using accuracy, precision/recall (since dropout is often imbalanced).
Insight: Key predictors might include socio-economic status, academic performance, and engagement
metrics. Typically, lower grades and low parental support correlate with higher dropout risk.
Dataset: Survey scores and customer info for an e-commerce platform. Task is to predict if a customer is
“satisfied” (CSAT) or not.
Workflow:
- Data integration: merge customer survey responses with purchase history or demographics using
[Link]() .
- EDA: Look at satisfaction scores distribution, and correlate CSAT with number of purchases or support
12
calls.
- Feature engineering: Create features like average spend, frequency of purchases.
- Handle imbalanced classes if few are unsatisfied (see next section).
- Train models (e.g., XGBoost) and measure metrics like ROC AUC.
Insight: It might be found that customers with more service tickets are less satisfied, or that repeat
customers tend to give higher satisfaction.
Each case study illustrates how techniques (cleaning, encoding, EDA, modeling) come together. In a full
study guide, these cases would include step-by-step code with explanations and visualizations from start to
finish.
5. D. Children in third-class
11. Which metric is crucial when dealing with imbalanced classes (e.g., churn dataset)?
13
merged = [Link](df_customers, df_orders, how='inner', on='customer_id')
• how='inner' yields rows where customer_id exists in both tables. Other options: 'left' ,
'right' , 'outer' .
• on='customer_id' specifies the key column to join.
• This creates a single DataFrame merged with columns from both sources aligned by customer.
If joining on index, you can set left_index=True or use [Link]() . Concatenation ( [Link] ) is
another method for stacking data.
Merging is used to enrich datasets. For instance, merge a demographic table with purchase data, or
combine survey responses with transaction logs. Always check for unintended duplication or missing
entries after merging (e.g., ensure many-to-many joins behave as expected).
After merging, proceed to clean or engineer features on the unified dataset. This step often reveals
inconsistencies (e.g., mismatched IDs) requiring further cleaning.
6. If two DataFrames have no columns in common, which merge key could you use?
References
14
One popular method is SMOTE (Synthetic Minority Over-sampling Technique). SMOTE generates
synthetic samples of the minority class to balance the dataset. According to the imbalanced-learn library
documentation, SMOTE “performs over-sampling using the Synthetic Minority Over-sampling
Technique” 16 . It works by taking each minority class sample and introducing synthetic examples along the
line segments joining that sample and its nearest minority neighbors. In other words, it interpolates new
points between existing minority points 17 . In practice:
• After fit_resample , X_resampled contains additional synthetic minority rows, making classes
more balanced.
• Note: SMOTE should be applied only to training data after splitting, to avoid data leakage.
SMOTE (and variants like SMOTENC for categorical features) are widely used. Be aware that over-sampling
can risk overfitting minority examples, so sometimes undersampling or combined methods (SMOTE +
Tomek links) are used. The key is balancing without losing information or introducing bias.
After resampling, proceed to train classifiers on the balanced data. You should evaluate performance using
metrics sensitive to imbalance (recall, precision, F1, ROC AUC) rather than accuracy alone.
5. D. Dimensionality reduction.
11. Why must you avoid applying SMOTE before train-test split?
15
References
Preventing data leakage: Data leakage occurs when information from the test set influences the training
model, leading to overly optimistic evaluations. A common mistake is performing preprocessing (like scaling
or imputation) on the entire dataset before splitting. Instead, always split first, then fit transformers on
X_train only. For example:
If you scaled before splitting, information about the test data (e.g., the true range of values) would leak into
the train scaler. MachineLearningMastery emphasizes correct workflows: perform data preparation within
cross-validation or after splitting to avoid leakage 19 . Their example shows using pipelines and cross-
validation to ensure no leakage, which slightly improved model performance when done properly 20 .
Always keep the test set completely separate until final evaluation. Use cross-validation on the training set
for model selection, but never peek at test labels during training or preprocessing.
16
3. B. Separate train and test subsets of features and target. (Correct)
4. C. The confusion matrix.
5. D. A merged DataFrame.
12. A. Splitting the data after scaling with the entire dataset. (Correct)
13. B. Stratifying splits.
14. C. Using cross-validation on training data only.
15. D. Imputing missing values on train set only.
References
For multi-class classification, metrics can be averaged (‘macro’, ‘micro’, ‘weighted’). Scikit-learn’s
classification_report gives precision, recall, F1 for each class.
ROC Curve and AUC: For binary classifiers, plot the Receiver Operating Characteristic (ROC) curve. The ROC
curve is a plot of the True Positive Rate (recall) vs False Positive Rate at various thresholds 23 . The Area
Under the Curve (AUC) summarizes it: “the probability that the model will rank a randomly chosen positive
instance higher than a negative one” 24 . AUC ranges from 0.5 (random) to 1.0 (perfect). A higher AUC
indicates better overall discrimination between classes.
17
Example: After predicting probabilities y_proba with a model:
Regression metrics: For predicting numeric values, common metrics include: - Mean Squared Error (MSE):
Average of squared differences (lower is better). sklearn’s mean_squared_error describes it as “Mean
squared error regression loss.” 25 .
- Root MSE (RMSE): Square root of MSE, in the same units as the target.
- Mean Absolute Error (MAE): Average absolute difference (less sensitive to outliers than MSE).
- R² (Coefficient of Determination): Proportion of variance explained by the model (ranges 0–1; higher is
better).
Always choose metrics that align with your problem. For imbalanced classification, consider precision-
recall or ROC AUC over accuracy. For regression, compare MSE/RMSE or MAE, and visualize residuals to
detect bias.
1. Precision measures:
2. A. TP/(TP+FN)
3. B. TP/(TP+FP) (Correct)
4. C. (TP+TN)/Total
5. D. TN/(TN+FP)
7. A. Perfect classification.
8. B. Random guessing. (Correct)
9. C. Cannot tell.
10. D. Overfitting.
18
References
Precision and recall definitions 21 22 ; ROC AUC interpretation 24 ; regression loss function descriptions
25 .
This comprehensive study guide covers the data science workflow from Python basics through data cleaning,
visualization, feature engineering, analysis, and model evaluation. It weaves together concepts, examples, and
case studies to build a solid foundation for beginner to intermediate learners in Python-based data science.
19
1 Python Overview
[Link]
3 [Link]
[Link]
17 ML | Handling Imbalanced Data with SMOTE and Near Miss Algorithm in Python - GeeksforGeeks
[Link]
20
22 recall_score — scikit-learn 1.7.1 documentation
[Link]
21