.query
with Pandas >= 0.25.0:August 2019 updated answer
Since Pandas >= 0.25.0 we can use the query
method to filter dataframes with Pandas methods and even column names which have spaces. Normally the spaces in column names would give an error, but now we can solve that using a backtick (`) - see GitHub:
# Example dataframe
df = pd.DataFrame({'Sender email':['[email protected]', "[email protected]", "[email protected]"]})
Sender email
0 [email protected]
1 [email protected]
2 [email protected]
Using .query
with method str.endswith
:
df.query('`Sender email`.str.endswith("@shop.com")')
Output
Sender email
1 [email protected]
2 [email protected]
Also we can use local variables by prefixing it with an @
in our query:
domain = 'shop.com'
df.query('`Sender email`.str.endswith(@domain)')
Output
Sender email
1 [email protected]
2 [email protected]