1. Home
  2. Explore
  3. Computer Science
  4. Data Science Basics with Python

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Data Science Basics with Python

Data Science Fundamentals with Python

Setup and Tools

Visual Studio Code and Anaconda

To get started with data science in Python, install Visual Studio Code (VS Code) as the code editor and Anaconda as a package manager and environment manager. Anaconda simplifies installing data science libraries like NumPy, Pandas, and Matplotlib. A short tutorial video shows how to install Anaconda in a few minutes.

Jupyter Notebooks

Data scientists frequently use Jupyter Notebooks – interactive documents that mix code, text, and visualizations. In VS Code, install the Python extension (which includes Jupyter support). Create a new notebook file (.ipynb) and start coding in cells. Cells can be either code (Python) or Markdown (for annotations). Running a cell executes the code and shows output below it.

Markdown cells allow adding formatted text, headings, and explanations directly into the notebook, making it easy to document the analysis.


Python Basics for Data Science

Lists vs NumPy Arrays

Python lists are flexible but not optimized for numerical operations. NumPy arrays (numpy.array) are designed for fast mathematical computations.

  • List multiplication: data * 2 duplicates the list (e.g., [1,2,3] * 2 gives [1,2,3,1,2,3]).

  • NumPy array multiplication: grades * 2 multiplies each element (e.g., array [1,2,3] * 2 → [2,4,6]).

Create a NumPy array by passing a list to np.array():

import numpy as np
grades = np.array(data)

Accessing Array Elements

Arrays are zero-indexed – the first element is at index 0. Use square brackets with the index:

  • grades[0] → first element

  • grades[2] → third element

Get the shape (number of elements) of an array with grades.shape.

Basic Operations on Arrays

Compute the mean (average) of an array: np.mean(grades) or grades.mean().

Combine multiple arrays into one 2D array by passing a list of arrays to np.array():

student_data = np.array([study_hours, grades])

Accessing elements in a 2D array: student_data[0][0] gives the first element of the first array (study hours). student_data[1][0] gives the first grade.


Data Analysis with Pandas

Creating DataFrames

Pandas provides the DataFrame – a table-like structure with named columns, similar to a spreadsheet. Import pandas and create a DataFrame from a dictionary:

import pandas as pd
df_students = pd.DataFrame({
    'name': names,
    'study_hours': student_data[0],
    'grade': student_data[1]
})

View the DataFrame by printing it or using the Variable Explorer in VS Code.

Accessing and Filtering Data

  • Loc method: df_students.loc[5] returns the row at index 5 (e.g., Vicky's data).

  • Loc with column: df_students.loc[5, 'grade'] returns just the grade of that row.

  • Column access with dot: df_students.grade returns the entire grade column.

  • Boolean filtering: df_students[df_students.name == 'Vicky'] returns rows where name is Vicky.

  • Query method: df_students.query('name == "Vicky"') achieves the same.

Handling Missing Values

Real-world data often has null values. Detect them with df_students.isnull(). Use .sum() to count missing values per column.

Two common strategies:

  1. Fill with mean: df_students['study_hours'].fillna(df_students.study_hours.mean()) replaces missing values with the column average.

  2. Drop rows with nulls: df_students.dropna(axis=0) removes any row that contains a null value (axis=0 for rows, axis=1 for columns).

Best practice: Dropping rows is often preferred to avoid introducing bias, but it reduces sample size.

Adding Columns (Pass/Fail)

Create a new column indicating pass/fail (e.g., pass if grade >= 60):

passed = pd.Series(df_students.grade >= 60)
df_students = pd.concat([df_students, passed.rename('Passed')], axis=1)

axis=1 adds the series as a new column.

Grouping and Aggregations

Use groupby() to split data into groups (e.g., passed vs failed) and compute statistics:

  • Count per group: df_students.groupby('Passed').name.count()

  • Mean of multiple columns: df_students.groupby('Passed')[['study_hours', 'grade']].mean()

Sorting Data

Sort a DataFrame by a column:

df_students = df_students.sort_values('grade', ascending=True)   # lowest first
df_students = df_students.sort_values('study_hours', ascending=False)  # highest first

Assign the result back to the variable to persist the change.


Data Visualization with Matplotlib

Bar Charts

Matplotlib is the standard plotting library. Import it as:

import matplotlib.pyplot as plt

Create a simple bar chart of student names vs grades:

plt.bar(df_students.name, df_students.grade)
plt.show()

Customizing Charts

Improve readability with:

  • Title: plt.title('Student Grades')

  • X-axis label: plt.xlabel('Name')

  • Y-axis label: plt.ylabel('Grade')

  • Rotate x-ticks: plt.xticks(rotation=90) prevents overlapping names.

  • Bar color: plt.bar(..., color='orange')

Subplots (Multiple Charts in One Figure)

A figure can contain multiple axes (plots). Use plt.subplots(rows, cols):

fig, (ax0, ax1) = plt.subplots(1, 2, figsize=(10,4))
  • ax0 and ax1 are the two axes. Use methods like ax0.bar(...), ax0.set_title(...), ax1.pie(...).

  • Finally call fig.show().

Pie Charts

Create a pie chart of pass/fail counts:

pass_counts = df_students.Passed.value_counts()
ax1.pie(pass_counts, labels=pass_counts.index)
ax1.set_title('Passing Grades')

Plotting Directly from DataFrames

Pandas integrates with Matplotlib – call .plot() directly on a DataFrame:

df_students.plot(kind='bar', x='name', y='grade', figsize=(10,4), color='green')

This is often simpler than using Matplotlib directly.


Statistics and Distributions

Histograms and Data Distribution

A histogram shows how data is distributed across bins.

grades = df_students.grade
plt.hist(grades, bins=10)   # bin count optional
plt.title('Data Distribution')
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.show()

The histogram reveals the shape of the sample – often symmetric with most values around the center.

Central Tendency

Three measures of the "middle" of the data:

  • Mean: arithmetic average (df_students.grade.mean())

  • Median: middle value when sorted (df_students.grade.median())

  • Mode: most frequent value – may be multiple; get first with df_students.grade.mode()[0]

Add vertical lines to the histogram to visualize these:

plt.axvline(mean_val, color='cyan', label='Mean')
plt.axvline(median_val, color='red', label='Median')
plt.axvline(mode_val, color='yellow', label='Mode')

Box Plots and Quartiles

A box plot displays data quartiles and outliers.

plt.boxplot(grades, vert=False)   # horizontal orientation
plt.title('Data Distribution')
plt.show()
  • The box represents the interquartile range (IQR: 25th to 75th percentile).

  • The line inside the box is the median.

  • Whiskers extend to the minimum and maximum non-outlier values.

  • Points beyond whiskers are outliers.

Combine histogram and box plot in one figure using subplots for a comprehensive view.

Probability Density Function (Bell Curve)

The density plot (smoothed version of histogram) shows the probability distribution.

df_students.grade.plot(kind='density')
plt.title('Data Density')
plt.show()

This creates a bell‑shaped curve for normally distributed data.

Variance and Standard Deviation

Variance measures how far data points spread from the mean. It is the average of squared differences from the mean:

Variance=∑i=1n(xi−xˉ)2n\text{Variance} = \frac{\sum_{i=1}^{n} (x_i - \bar{x})^2}{n}Variance=n∑i=1n​(xi​−xˉ)2​

Standard deviation is the square root of variance:

σ=Variance\sigma = \sqrt{\text{Variance}}σ=Variance​

In Python, compute directly on a DataFrame column:

  • df_students.grade.var() – variance

  • df_students.grade.std() – standard deviation

Range and Descriptive Statistics

Range = max – min. The .describe() method on a DataFrame returns all key statistics: count, mean, std, min, quartiles, max.

For a normal distribution, approximately 68% of values fall within one standard deviation of the mean.


Exploring Relationships Between Variables

Comparing Numeric and Categorical Data

Use a grouped box plot to compare a numeric variable across categories (e.g., study hours per pass/fail status):

df_students.boxplot(column='study_hours', by='Passed', figsize=(8,5))

This visually confirms that students who passed studied more hours on average.

Normalization (Min‑Max Scaling)

When comparing two numeric variables with different scales (e.g., grade 0–100 vs study hours 0–20), normalize both to a common range (0 to 1) using a MinMaxScaler from sklearn.preprocessing.

from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
df_normalized = df_students[['name', 'grade', 'study_hours']].copy()
df_normalized[['grade', 'study_hours']] = scaler.fit_transform(df_normalized[['grade', 'study_hours']])

Now plot both together on a bar chart to see the relationship.

Correlation

Correlation coefficient (Pearson’s r) measures the strength and direction of a linear relationship between two numeric variables. Ranges from -1 (negative correlation) to +1 (positive correlation). 0 means no linear correlation.

correlation = df_normalized.grade.corr(df_normalized.study_hours)

A value like 0.91 indicates a strong positive correlation – as study hours increase, grade tends to increase.

Correlation does not imply causation. A strong correlation does not prove that one variable causes changes in the other.

Scatter Plots and Linear Regression

A scatter plot shows each data point as a dot on an X–Y grid.

plt.scatter(df_students.study_hours, df_students.grade)
plt.title('Study Time vs Grade')
plt.xlabel('Study Hours')
plt.ylabel('Grade')
plt.show()

To see the trend more clearly, fit a regression line using linear regression – which uses the slope‑intercept form: y=mx+by = mx + by=mx+b.

  • mmm = slope (rate of change)

  • bbb = y‑intercept (value of y when x=0)

Use SciPy to compute the regression line:

from scipy import stats
slope, intercept, r_value, p_value, std_err = stats.linregress(df_regression.study_hours, df_regression.grade)

Then calculate predicted y values (y^\hat{y}y^​) for each x:

df_regression['fx'] = slope * df_regression.study_hours + intercept

Plot the line on top of the scatter plot:

plt.plot(df_regression.study_hours, df_regression.fx, color='cyan')

This line of best fit minimizes the sum of squared errors (least squares method).

Making Predictions

With slope mmm and intercept bbb, a prediction function can estimate a grade given study hours:

def predict(study_hours):
    return 6.31 * study_hours + (-17.92)   # example values
predict(14)   # returns ~70

This is a simple linear regression model – a foundational machine learning algorithm. By fitting a line to data, the model can predict outcomes for new inputs.

Understanding slope‑intercept form (y=mx+by = mx + by=mx+b) from algebra is directly applied here to build a predictive model from data.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent