0% found this document useful (0 votes)
23 views3 pages

Python Data Science Cheat Sheet

This cheat sheet provides essential Python Data Science operations, covering key libraries such as NumPy, Pandas, Matplotlib, Seaborn, and Scikit-learn. It includes code snippets for creating arrays, DataFrames, visualizations, and implementing machine learning models. A quick reference table is also included for easy recall of import statements and functionalities.

Uploaded by

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

Python Data Science Cheat Sheet

This cheat sheet provides essential Python Data Science operations, covering key libraries such as NumPy, Pandas, Matplotlib, Seaborn, and Scikit-learn. It includes code snippets for creating arrays, DataFrames, visualizations, and implementing machine learning models. A quick reference table is also included for easy recall of import statements and functionalities.

Uploaded by

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

Python Data Science Cheat Sheet

Table of Contents
1. Numpy Essentials
2. Pandas Basics
3. Data Visualization (Matplotlib/Seaborn)
4. Scikit-learn Machine Learning
5. Useful Code Snippets

1. Numpy Essentials

import numpy as np

# Create arrays
arr = [Link]([1, 2, 3])
zero_arr = [Link]((3, 2))
one_arr = [Link](5)
rand_arr = [Link](3, 3)

# Indexing and slicing


arr[0], arr[-1], arr[1:3]

# Operations
[Link](), [Link](), [Link]()
arr2 = arr * 2

# Reshape
reshaped = [Link]((1, 3))

2. Pandas Basics

import pandas as pd

# Create DataFrame

data = {'A': [1, 2, 3], 'B': [4, 5, 6]}


df = [Link](data)

# Read CSV
# df = pd.read_csv('[Link]')

# Basic operations
summary = [Link]()
col_a = df['A']
filtered = df[df['A'] > 1]

df['C'] = df['A'] + df['B'] # Create new column

# Groupby
grouped = [Link]('A').sum()

3. Data Visualization

import [Link] as plt


import seaborn as sns

# Line plot
[Link]([1,2,3], [4,5,6])
[Link]('Line Plot')
[Link]()

# Bar plot
[Link](['A','B','C'], [3,7,2])
[Link]('Bar Plot')
[Link]()

# Seaborn heatmap
[Link]([[1,2],[3,4]])
[Link]()

4. Scikit-learn Machine Learning

from sklearn.linear_model import LinearRegression


X = [[1], [2], [3]]
y = [2, 4, 6]

model = LinearRegression()
[Link](X, y)
pred = [Link]([[4]]) # Output: [8]

# Train-test split
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

5. Useful Snippets

# List comprehension
squares = [x**2 for x in range(5)]

# Lambda function
add = lambda a, b: a + b
# Dictionary comprehension
my_dict = {x: x*2 for x in range(3)}

# Enumerate
for idx, val in enumerate(['a','b','c']):
print(idx, val)

Quick Reference Table


Library Import Statement Key Functionality

NumPy import numpy as np Arrays, math ops

pandas import pandas as pd DataFrames

matplotlib import [Link] Plotting

seaborn import seaborn as sns Stats graphing

scikit-learn from sklearn... ML models, Split

This cheat sheet summarizes essential Python Data Science operations for quick recall.

Common questions

Powered by AI

NumPy arrays can be created using methods like `np.array()`, `np.zeros()`, `np.ones()`, and `np.random.rand()`. These methods generate arrays with specified shapes and initial values. Arrays can be manipulated in terms of their shape using the `reshape()` method, as demonstrated with `arr.reshape((1, 3))`. Mathematical operations can be performed element-wise or as aggregate operations like `mean()`, `sum()`, and `std()` to analyze array properties .

Groupby operations in pandas allow summarizing data by categories through aggregation functions. For example, `df.groupby('A').sum()` groups the DataFrame by unique values in column 'A' and calculates the sum of all other columns for each group. This function facilitates analyses like finding totals, averages, or other statistics across categories, enabling users to discover patterns and correlations in data easily .

Evaluating and validating machine learning models in scikit-learn involves strategies like the train-test split, which divides the dataset into training and validation sets to prevent overfitting. Additionally, cross-validation and performance metrics such as mean squared error or accuracy are critical to ensure models generalize well to unseen data. These techniques are crucial as they provide reliable estimates of a model's predictive performance and highlight potential biases or variance issues in model training .

The train-test split in machine learning is performed using the `train_test_split()` function from scikit-learn, which divides the dataset into training and testing subsets. The significance of this process lies in its role in evaluating the model's ability to generalize to new, unseen data. It's crucial for unbiased assessment of model performance to avoid overfitting the training data. In the provided example, `X` and `y` are split into `X_train`, `X_test`, `y_train`, and `y_test` with a test size specified as 20% of the data .

Dictionary comprehensions in Python provide a compact way to create dictionaries programmatically, offering both efficiency and readability. The syntax `{key: value for element in iterable}` allows for applying operations or filters directly within the comprehension. In the example `my_dict = {x: x*2 for x in range(3)}`, a dictionary is created where each integer from 0 to 2 is mapped to its double. This method reduces the amount of code compared to using a loop, improving performance, especially with large data sets .

Seaborn complements Matplotlib by providing a high-level interface for statistical graphics, which often require less code to generate complex plots. For example, seaborn can generate a heatmap using `sns.heatmap([[1,2],[3,4]])`, automatically handling aspects like color mapping and annotations. In contrast, Matplotlib offers more fine-grained control, as seen with `plt.plot()` for line plots and `plt.bar()` for bar plots, requiring more manual tuning of plot parameters. Together, they cover a broad range of visualization needs from basic to intricate statistical plotting .

List comprehensions facilitate efficient data processing by providing a succinct syntax for creating lists based on existing iterables. They replace loops with a single line, enhancing readability and execution speed. For example: `squares = [x**2 for x in range(5)]` creates a list of squared numbers from 0 to 4. This approach reduces the need for explicitly initializing a list and appending elements, streamlining the code .

Pandas primarily uses DataFrames for data manipulation, offering labeled index and column-data access, which differs from the numerical and array-centric approach of NumPy. In Pandas, you can perform operations like filtering with conditions (e.g., `df[df['A'] > 1]`), create new columns through operations like `df['C'] = df['A'] + df['B']`, and apply aggregate functions across groups (e.g., `df.groupby('A').sum()`). These functions offer more structured and high-level interfaces for data exploration and manipulation compared to NumPy .

Reshaping arrays in NumPy is crucial for adapting data into required dimensions for different operations or algorithms, especially in machine learning and data processing where input feature shapes must match model shapes. The `reshape()` method in NumPy, as used in `arr.reshape((1, 3))`, allows changing an array's shape while maintaining the same elements in a different structural layout. It is a versatile tool that supports reshaping without altering the underlying data, thereby enhancing flexibility in various applications .

Lambda functions in Python are small anonymous functions defined with the `lambda` keyword, mainly used for concise operations. They are useful for quick, throwaway functions that don't require a full function definition via `def`. As demonstrated in the document, `add = lambda a, b: a + b` creates a function that adds two numbers. This approach is beneficial in cases like sorting or filtering when quick, inline calculations are needed without the overhead of defining a full function .

You might also like