You Should Know These Tricks as a Data Scientist
By Gencay
Published: 2024-02-20
URL: https://www.learnwithmeai.com/p/5-pandas-tricks-that-will-blow-your

\Created with Abidin Dino AI, to reach it, consider being Paid subscriber to LearnAIWithMe,here\
Data is a precious thing and will last longer than the systems themselves.
Tim Berners-Lee
Today, we’re going to look closely at how we can work with this precious data using Pandas, and find out interesting things even in normal tasks.
In this article, I'll guide you through these game-changing techniques, ensuring you wield pandas like never before.
Simplified Data Filtering with Query
The Pandas query() feature, will give you a concise way to select rows from a Dataframe based on condition
Let’s say you are analyzing a dataset, and you want to quickly find all transactions > $500.
Instead of using complicated methods, you can use query() to express this condition directly. Let’s see the code.
import pandas as pd
# Sample dataset of retail store sales
data = {'Product': ['Toy', 'Book', 'Clothing', 'Electronics'],
'Sales': [150, 200, 550, 1200]}
df = pd.DataFrame(data)
# Using query() to find high-value sales
high_value_sales = df.query('Sales > 500')
high_value_sales
Here is the output.

In this one;
- We first create a DataFrame
dfwith sales data for different products.
- Next, we use the
query()method to find and display all rows where sales are greater than $500.
Master Time Series Analysis with Pandas’ Resampling
Pandas makes it easy to handle data that changes over time. This kind of data is marked by dates or times. For example, someone studying website visits might look at the number of visitors each day.
With Pandas, you can group this day-by-day data into weeks or months. This helps you see trends over a longer period.
import pandas as pd
import numpy as np
# Create a range of dates
date_range = pd.date_range(start='1/1/2022', end='12/31/2022', freq='D')
# Simulate daily website traffic data
traffic_data = np.random.randint(low=100, high=1000, size=len(date_range))
# Create DataFrame
df = pd.DataFrame({'Date': date_range, 'Traffic': traffic_data})
df.set_index('Date', inplace=True)
# Resample and calculate the monthly average
monthly_traffic = df.resample('M').mean()
monthly_traffic
Here is the output.

\SS of Output\
In this example
- First we did generate a data, that shows daily visits to a website for a whole year, by generating random numbers in given interval.
- Next, we choose 'M' for monthly. This tells Pandas to put the data into monthly groups and find the average visits for each month.
This way, we can spot trends over time, such as if more people visit the site in some months, without worrying about the ups and downs of each day.
Categorical Data in Pandas
When working with a data, Pandas’ support for categorical data types can be a life-saver.
For instance, a data scientist analyzing customer feedback might categorize responses into :
- “Positive”
- “Neutral”
- “Negative”
Using the categorical data type for these categories can make the analysis more efficient and the data easier to work with, like applying ML model, or filtering easily.
import pandas as pd
# Sample data: Customer feedback
data = {'Feedback': ['Positive', 'Negative', 'Neutral', 'Positive', 'Negative']}
df = pd.DataFrame(data)
# Convert the 'Feedback' column to a categorical data type
df['Feedback'] = df['Feedback'].astype('category')
print(df['Feedback'])
print(df['Feedback'].cat.codes)
Let’s see the output.

\SS of Output\
In this code, we create a DataFrame containing customer feedbacks. We then convert the ‘Feedback’ column to a categorical type using the astype('category') method.
This not only reduces memory usage but also allows us to build Machine Learning Model on it.
Multi-Dimensional Data Analysis in Pandas
Pandas has a tool called MultiIndex, or hierarchical indexing. It lets you handle data with more than two levels, like in a table, but easier. MultiIndex organizes this data so it’s simple to look at by both time and place at the same time. Let’s see one example data to do that.
import pandas as pd
# Sample sales data
data = {
'Year': [2020, 2020, 2021, 2021],
'Quarter': ['Q1', 'Q2', 'Q3', 'Q4'],
'Sales': [25000, 30000, 40000, 35000]
}
# Create DataFrame
df = pd.DataFrame(data)
# Set MultiIndex
df.set_index(['Year', 'Quarter'], inplace=True)
df
Here is the output.

\SS of Output\
In this code, we create a DataFrame with sales data, then use the set\_index() method with a list of columns ('Year' and 'Quarter') to create a MultiIndex.
This helps us to easily perform operations that consider both the year and the quarter, such as slicing the data to analyze sales trends over time across different quarters.
Optimizing Memory
Pandas has special tools to use less memory, which is great for big datasets. It means you can work with a lot of data without using too much computer memory.
For example, if a data scientist has millions of records to look at, Pandas helps make the work fast and able to handle more data. Let’s see one example.
import pandas as pd
# Sample large dataset
data = {'Name': ['John', 'Ana', 'Peter', 'Linda'],
'Age': [28, 34, 45, 32],
'Income': [50000, 60000, 80000, 75000]}
df = pd.DataFrame(data)
# Before optimization: Check memory usage
print("Before optimization:")
print(df.info(memory_usage='deep'))
Here is the output.

\SS of Output\
Now let’s do optimization and see again. Here is the code.
# Optimize by converting to appropriate data types
df['Age'] = df['Age'].astype('int8')
df['Income'] = df['Income'].astype('int32')
# After optimization: Check memory usage
print("\nAfter optimization:")
print(df.info(memory_usage='deep'))
Here is the output.

\SS of Output\
Final Thoughts
Thanks for reading this one. Pandas is too important if you are in to Data Analysis. Because it has really too many features for you to do this data analysis and manipulation easily.
Thanks for reading!