Pandas is one of the most important Python library in AI
By Gencay
Published: 2024-04-05
URL: https://www.learnwithmeai.com/p/5-pandas-maneuvers-you-should-know

\Created with Abidin Dino AI, to reach it, consider being Paid subscriber to LearnAIWithMe,here\
Without data, you're just another person with an opinion." –
W. Edwards Deming.
Capturing the essence of this quote, mastering Pandas is pivotal for anyone looking to be a part of AI community.
I'll guide you through five essential Pandas maneuvers that will not only introduce you to Pandas but also aim to enhance your current skills.
Here is the link to LearnAIWithMe GPT.
Unlock the Power of Data: Load Any Data into Pandas

\Photo byMike van den BosonUnsplash\
Imagine standing at the doorstep of a vast library. Each book offers insights into different worlds, stories, and pieces of knowledge.
In the realm of data science, these books are your datasets, and Pandas is the key to unlocking these insights.
As a beginner, your first step into this expansive library begins with learning how to open the door—loading data into Pandas.
The Magic Wand: read\_csv()
CSV files are the universal language of data. They're simple, ubiquitous, and your first encounter with data will likely be in this format. With Pandas, bringing this data into your Python environment is as easy as casting a spell:
import pandas as pd
# Cast your spell here
df = pd.read_csv('path/to/your/magical_data.csv')
# Peek into the first few rows of your dataset
print(df.head())
This simple incantation transforms your raw data into a structured DataFrame, ready for exploration.
Unraveling Scrolls: read\_excel()
Excel files, with their sheets and cells, are like ancient scrolls—rich with information but slightly more complex to navigate. Fear not, for Pandas handles these with ease as well:
# Another spell to reveal the secrets within
df_excel = pd.read_excel('path/to/your/mystical_data.xlsx', sheet_name='YourAdventure')
# Discover the first few lines of the story
print(df_excel.head())
Just like that, data hidden in the sheets of an Excel file unfolds before you, structured and accessible.
With these spells in your grimoire, any data, be it in CSVs, Excel sheets becomes accessible and ready for your analytical quests. This is the beginning of your journey into the vast and mystical world of data science with Pandas.
First Date with Your Data: Discover Its Secrets in Minutes

\Photo byfreestocksonUnsplash\
You’re eager to learn everything about your partner (the dataset), from their characteristics to their deepest secrets. This stage is about making a great first impression, understanding the basics, and setting the stage for a deeper connection.
The Welcoming: head() and tail()
Just like starting a conversation, the head() and tail() functions in Pandas allow you to take a sneak peek at your data, providing a glimpse into its structure and content.
# Greet your data
print("First glimpse with head():")
print(df.head())
# And don't forget to say goodbye with tail():
print("\nA parting glance with tail():")
print(df.tail())
These functions are your first exchange of pleasantries, showing you the opening and closing lines of your data's story.
Unraveling the Mysteries: info() and describe()
To delve deeper, you’ll want to explore the essence of your dataset. The info() method reveals the backbone of your dataset—data types, missing values, and memory usage—offering a snapshot of its health and composition.
# Unveiling the dataset's skeleton
print(df.info())
Meanwhile, describe() is like uncovering the heartbeats of your data. It shares the tales of central tendencies, dispersion, and shape of the dataset’s numerical features.
# Listening to the heartbeat
print(df.describe())
These functions allow you to uncover the dataset's essence, preparing you for deeper exploration and analysis.
Let’s test them by using fake dataset, and applying all of these ones above.
# Simulating the loading of the CSV file into a DataFrame
data = {
'Region': ['North', 'South', 'East', 'West', 'East'],
'Product': ['Widgets', 'Gadgets', 'Doodads', 'Widgets', 'Gadgets'],
'Sales': [200, 450, 300, 150, 400]
}
df = pd.DataFrame(data)
# First impressions with head() and tail()
print("The first glimpse with head():\n", df.head(), "\n")
print("A parting glance with tail():\n", df.tail(), "\n")
# Understanding the structure with info()
print("Unraveling the mysteries with info():")
df.info()
# The essence of your data with describe()
print("\nListening to the heartbeat with describe():\n", df.describe())
Here is the output.

Become a Data Ninja: Master the Art of Slicing and Dicing with Pandas

\Photo byAbolfazl eslamionUnsplash\
Now that you're acquainted with your dataset, imagine yourself as a data ninja, ready to slice through the data with precision and agility.
The Blade of Selection: Accessing Columns and Rows
Your first tool as a data ninja is the ability to select specific columns or rows. Think of this as choosing the right weapon for your mission.
# Selecting a single column - like drawing a single arrow
print("A glance at the 'Sales' column:")
print(df['Sales'])
# Selecting multiple columns - arming yourself with more than one tool
print("\nA broader view with 'Product' and 'Sales' columns:")
print(df[['Product', 'Sales']])
The Stealth of Filtering: Using Conditions to Find Data
Next, enhance your stealth by using conditions to filter data. This is like moving unseen, only engaging the targets that match your criteria.
# Filtering data - the ninja way
print("Finding all products with sales over $500:")
filtered_data = df[df['Sales'] > 500]
print(filtered_data)
The Agility of Row Selection: loc and iloc
Your agility as a data ninja comes from quickly moving through rows using loc (label-based) and iloc (position-based) selectors. Whether it's a specific row or a range, you can swiftly pinpoint your target.
# Using 'loc' to select by label
print("Details of the third sale:")
print(df.loc[2])
# Using 'iloc' for position-based selection
print("\nFirst two sales details:")
print(df.iloc[:2])
These techniques allow you to navigate and manipulate your dataset with the precision of a seasoned ninja, making sure you always hit your mark.
Code Example for Slicing and Dicing Data
Now let’s again create a dataframe, and apply what we learn.
# Creating the DataFrame from the provided data
data = {
'Month': ['January', 'February', 'March', 'April', 'May'],
'Store': ['Store A', 'Store B', 'Store A', 'Store C', 'Store B'],
'Product': ['Widgets', 'Gadgets', 'Doodads', 'Widgets', 'Gadgets'],
'Sales': [120, 150, 200, 90, 180]
}
df = pd.DataFrame(data)
# Selecting a single column - like focusing on a target
print("Focus on 'Sales':\n", df['Sales'], "\n")
# Filtering data - honing in on your quarry
print("Sales over 150:\n", df[df['Sales'] > 150], "\n")
# Using 'loc' to select rows by label/index
print("March Sales Details:\n", df.loc[df['Month'] == 'March'], "\n")
# Using 'iloc' for position-based selection
print("First two records:\n", df.iloc[:2])
Here is the output.

Alchemy in Data Analysis: Transforming Base Data into Gold

\Photo byPretty DrugthingsonUnsplash\
In this magical phase of our journey, we become data alchemists, capable of transforming mundane information into insightful knowledge. This process involves creating new columns based on existing data, a practice that enriches our dataset with additional layers of meaning and utility.
The Transmutation Circle: Adding New Columns
Imagine drawing a transmutation circle that channels your analytical intent into creating new dimensions within your dataset. Adding a new column is as simple as defining the formula for your alchemical reaction.
# Creating a new column 'Revenue' by multiplying 'Sales' by a unit price
df['Revenue'] = df['Sales'] \* 10 # Assuming a unit price of 10 for simplicity
print("Dataset with the new 'Revenue' column:")
print(df)
This new column, 'Revenue', materializes from the existing 'Sales' data, offering a fresh perspective on the financial aspect of your dataset.
The Philosopher's Stone: Applying Functions to Columns
The real magic happens when you apply functions to your columns, turning them into powerful tools for insight. This is akin to using the philosopher's stone to transmute base metals into gold.
# A simple function to categorize sales into 'High' and 'Low'
def categorize_sales(amount):
return 'High' if amount > 500 else 'Low'
# Applying our function to the 'Sales' column
df['Sales_Category'] = df['Sales'].apply(categorize_sales)
print("Dataset with categorized sales:")
print(df)
By applying the categorize\_sales function to each value in the 'Sales' column, we've effectively enriched our dataset with meaningful classifications that can aid in further analysis.
Sample Dataset for Transformation:
We'll continue with the monthly\_sales dataset used in the previous section, which includes sales data for various products across different stores.
Let's transmute our existing data into new columns that offer additional layers of insight.
# Assuming the DataFrame 'df' is already created as before
# Adding a 'Sales Tax' column, assuming a 10% sales tax rate
df['Sales Tax'] = df['Sales'] \* 0.10
print("Dataset with Sales Tax:\n", df, "\n")
# Creating a new column to categorize sales performance
def categorize_performance(sales):
if sales < 100:
return 'Low'
elif sales <= 150:
return 'Medium'
else:
return 'High'
df['Performance'] = df['Sales'].apply(categorize_performance)
print("Dataset with Sales Performance Categorization:\n", df)
Here is the output.

These examples demonstrate the alchemical power of Pandas to enrich your data, turning the base metal of raw figures into the gold of actionable insights.
The Secret Society of Data: Unveiling Patterns with Grouping and Aggregation

\Photo byRoman MageronUnsplash\
In every dataset lies a secret society of patterns waiting to be discovered. Grouping and aggregating data is like being granted a key to their hidden meetings, where the collective behavior of data points reveals the bigger picture.
Gathering at the Round Table: Grouping Data
Think of grouping as gathering similar data points into circles, each sharing common traits. With the groupby() method, you can summon these groups based on one or more characteristics.
# Grouping sales data by 'Product'
grouped_data = df.groupby('Product')
print("Data grouped by 'Product':")
for name, group in grouped_data:
print(f"\n{name}:\n{group}")
This gathering allows you to observe how each product performs, setting the stage for deeper analysis.
Whispered Secrets: Aggregating Grouped Data
Aggregation is the act of listening to the whispered secrets of these groups, summarizing their tales into meaningful insights. Common aggregation functions include sum, mean, and count, each offering a different perspective on the group's behavior.
# Aggregating sales data to find the total sales per product
total_sales_per_product = grouped_data['Sales'].sum()
print("Total sales per product:")
print(total_sales_per_product)
This aggregation reveals not just individual performances but the strength of each product in numbers, offering clues to trends and preferences within your market.
The Alchemy of Multiple Aggregations
True mastery comes from combining multiple aggregation functions to extract a spectrum of insights from each group.
# Applying multiple aggregations
aggregated_data = grouped_data['Sales'].agg(['sum', 'mean', 'max'])
print("Aggregated sales data (Total, Average, Maximum) per product:")
print(aggregated_data)
This multifaceted approach unveils the richness of your dataset, from overall performance to peak achievements, illuminating the path to informed decisions.
Enhancing our Dataset for Grouping and Aggregation
For this exercise, we'll add a bit more complexity to our dataset to make the aggregation more illustrative.
Code Example
We will demonstrate how to group our data by certain columns and then apply aggregation functions to summarize the grouped data.
# Extending our DataFrame for more illustrative examples
data = {
'Month': ['January', 'February', 'March', 'April', 'May', 'January', 'February', 'March', 'April', 'May'],
'Store': ['Store A', 'Store B', 'Store A', 'Store C', 'Store B', 'Store A', 'Store B', 'Store A', 'Store C', 'Store B'],
'Product': ['Widgets', 'Gadgets', 'Doodads', 'Widgets', 'Gadgets', 'Gadgets', 'Widgets', 'Doodads', 'Gadgets', 'Widgets'],
'Sales': [120, 150, 200, 90, 180, 110, 160, 250, 130, 175]
}
df = pd.DataFrame(data)
# Grouping by 'Store' to understand sales distribution
store_sales_summary = df.groupby('Store')['Sales'].sum()
print("Total Sales by Store:\n", store_sales_summary, "\n")
# Further diving into the data by grouping by both 'Store' and 'Product'
store_product_sales_summary = df.groupby(['Store', 'Product']).agg({
'Sales': ['sum', 'mean', 'max']
})
print("Sales Summary by Store and Product:\n", store_product_sales_summary)
Here is the output.

Through grouping and aggregation, we've decoded the secret language of our dataset, unveiling the patterns that reside within
Learn Pandas with LearnAIWithMe

You can reach to LearnAIWithMe GPT from invited only notion page.
After starting a new conversation, here is the prompt you should use ;
I want to learn pandas
Here is the output of our special GPT;

Here you can ask whatever you want in your mind, this curriculum was generated just for you and includes every elements of Pandas.
Final Thoughts
With this, we conclude our guided exploration into Pandas for beginners, having traversed from loading and exploring data to slicing, dicing, transforming, and finally, revealing the hidden stories within through aggregation.
Thanks for reading this one! I hope your journey in AI has been started smoothly!