Python Dataframe Filter by Column Value
To filter a DataFrame by a specific column value in Python using pandas, you can follow these steps:
- Import the necessary libraries.
- Create your DataFrame.
- Use the
locorquerymethod 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']
}df = pd.DataFrame(data)# Step 3: Filter the DataFrame by the 'City' column valueGet Zeeshan Ali’s stories in your inbox
Join Medium for free to get updates from this writer.
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 BostonFiltered DataFrame:
Name Age City
0 Alice 25 New YorkIn 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.






