Python With Excel and Text Strings
Pandas Dataframes
Let’s now see how to filter on some complex conditions
Code:
import pandas as pd
df = pd.read_excel('europe_cities_by_sunshine.xlsx')
df[ ( (df['Year'] > 3000) & (df['Country'] == 'Cyprus') ) | ( (df['Year'] < 1200) ) ]
Explanation:
Now, we’re filtering on 3 conditions, but note the parentheses placement in the first two conditions. There is a parentheses around the first 2 conditions so we’re going ensure that the Year is above 3000 AND the country is Cyprus. But then, we added the OR operator and are also going to allow values with Year less than 1200 as well, so if it fits either the first 2 conditions, or the last condition, then it will be returned in the dataframe.