Sitemap
Zeeshan Ali

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

Python Dataframe Filter by Column Value

1 min readJul 21, 2023

To filter a DataFrame by a specific column value in Python using pandas, you can follow these steps:

  1. Import the necessary libraries.
  2. Create your DataFrame.
  3. Use the loc or query method to filter the DataFrame based on the desired column value.

Here’s an example of how to do it:

import pandas as pd
# Step 2: Create your DataFrame
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Emily'],
'Age': [25, 30, 22, 35, 28],
'City': ['New York', 'San Francisco', 'Los Angeles', 'Chicago', 'Boston']
}

Get Zeeshan Ali’s stories in your inbox

Join Medium for free to get updates from this writer.

df = pd.DataFrame(data)# Step 3: Filter the DataFrame by the 'City' column value
city_to_filter = 'New York'
filtered_df = df[df['City'] == city_to_filter]
# You can also use the query method to filter the DataFrame
# filtered_df = df.query("City == @city_to_filter")
print("Original DataFrame:")
print(df)
print("\nFiltered DataFrame:")
print(filtered_df)

Output:

Original DataFrame:
Name Age City
0 Alice 25 New York
1 Bob 30 San Francisco
2 Charlie 22 Los Angeles
3 David 35 Chicago
4 Emily 28 Boston
Filtered DataFrame:
Name Age City
0 Alice 25 New York

In this example, we filtered the DataFrame to include only the rows where the ‘City’ column has the value ‘New York’. You can replace 'New York' with any other city value you want to filter by.

--

--

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