Sitemap

Python Dataframe Filter and Matplotlib Implementation

2 min readJul 21, 2023

--

I understand you want to filter a Python DataFrame and use it in further operations. To do that, you can use the popular library called pandas, which provides powerful tools for data manipulation and analysis.

Assuming you already have pandas installed, here’s a step-by-step guide on how to filter a DataFrame and then perform some operations on the filtered data:

Get Zeeshan Ali’s stories in your inbox

Join Medium for free to get updates from this writer.

Step 1: Import the necessary libraries

import pandas as pd

Step 2: Create a DataFrame For demonstration purposes, let’s create a simple DataFrame containing some sample data:

data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva'],
'Age': [25, 30, 22, 27, 29],
'City': ['New York', 'San Francisco', 'Los Angeles', 'Chicago', 'Miami']
}
df = pd.DataFrame(data)

Your DataFrame df will look like this:

Name  Age           City
0 Alice 25 New York
1 Bob 30 San Francisco
2 Charlie 22 Los Angeles
3 David 27 Chicago
4 Eva 29 Miami

Step 3: Filter the DataFrame Now let’s say you want to filter the DataFrame to only include people who are older than or equal to 25 years old:

filtered_df = df[df['Age'] >= 25]

The filtered_df will now contain only the rows that meet the condition:

Name  Age           City
0 Alice 25 New York
1 Bob 30 San Francisco
3 David 27 Chicago
4 Eva 29 Miami

Step 4: Perform operations on the filtered DataFrame Now that you have the filtered DataFrame, you can perform various operations on it, such as calculating statistics or plotting the data:

# Calculate the average age of the filtered individuals
average_age = filtered_df['Age'].mean()
print("Average age:", average_age)
# Plot a bar chart showing the number of people in each city
import matplotlib.pyplot as plt
city_counts = filtered_df['City'].value_counts()
city_counts.plot(kind='bar')
plt.xlabel('City')
plt.ylabel('Number of People')
plt.title('Number of People in Each City')
plt.show()

Remember to adjust the operations based on your specific use case. Filtering the DataFrame allows you to work with a subset of data that meets your criteria, which can be extremely useful in data analysis and manipulation tasks.

Command to import matplotlib

pip install matplotlib

Run it in your terminal.

--

--

Zeeshan Ali
Zeeshan Ali

Written by Zeeshan Ali

I am a Python developer and I am here to share what i have learnt so far. Hope my posts will help you in your python development journey. www.letmeflutter.com