Filter Data
Lesson 9 of 19 in Coddy's Pandas Analytics course.
Pandas allow us to filter rows based on a specific condition. To filter rows, write the condition inside brackets:
filtered_df = df[df["number_column"] > 5]
filtered_df = df[df["string_column"] == "String Match"]To combine multiple conditions, use the & (and) keyword and the | or keyword. Every condition must be in parenthesis ():
filtered_df = df[(df['number_column'] >= 3) & (df['string_column'] == 'String Match')]The not keyword is ~ (not greater than 5):
filtered_df = df[~df["number_column"] > 5]To retrieve all of the not-empty values from a specific column:
filtered_df = df[~df["column"].isna()]To check if a value is in an array:
filtered_df = df[df['column'].isin(['value1', 'value2', 'value3'])]
Challenge
EasyThe CSV file stats.csv contains information about stats.
Here is the first 5 lines of the file:
ID,COUNTRY,COLOR,SKILL,SKILL_POINTS,UTILIZATION,IS_VALID,CATEGORY
1,France,Signal violet,marksmanship,14,0.1924,1,SHOW
2,Solomon Islands,Pearl violet,crocheting,4,0.6108,1,TREE
3,Germany,Bottle green,calligraphy,12,0.88646,0,SHOW
4,Mauritania,Fawn brown,paper cutting,9,0.058,1,JAPERetrieve only the rows that match the following criteria:
SKILL_POINTSis greater than7.UTILIZATIONis smaller or equal to0.7or greater than0.95.IS_VALIDequals one.CATEGORYis one of the following:JAPE,PLQR, andGHUP
Store the final result in the df variable.
Try it yourself
# pandas as pd is already imported
df = pd.read_csv("./stats.csv")
# Write your code below
All lessons in Pandas Analytics
4Data Analysis with Pandas
Descriptive StatisticsGrouping and Aggregating DataDifferent AggregationsMerge & Concat2Working with the DataFrame
Understanding DataFramesAccessing DataData Cleaning - Missing dataData Cleaning - More tools3Data Manipulation with Pandas
Return Requested ResultFilter DataAdd & DeleteModify DataModify StringsCustom Modifications