Let’s create a pattern dataframe having 3 columns and 4 rows. This dataframe is used for demonstration function.
import pandas as pd df = pd.DataFrame({"col1" : vary(1,5), "col2" : ['A A','B B','A A','B B'], "col3" : ['A A','A A','B B','B B'] })
Filter a price A A
in column col2
With the intention to do reference of a variable in question, that you must use @
.
newdf = df.question("col2 == 'A A'")
myval1 = 'A A' newdf = df.question("col2 == @myval1")
How one can cross column identify as a variable in question
As a substitute of filter worth we’re referring the column which we wish to use for subetting or filtering.
myvar1 = 'col2' newdf2 = df.question("{0} == 'A A'".format(myvar1))
{0} takes a price of variable myvar1.
"{0} == 'A A'".format(myvar1)
returns"col2 == 'A A'"
Incase you wish to cross a number of columns as variables in question. Right here we’re utilizing columns col2
and col3
.
myvar1 = 'col2' myvar2 = 'col3' newdf2 = df.question("{0} == 'A A' & {1} == 'B B'".format(myvar1, myvar2))
"{0} == 'A A' & {1} == 'B B'".format(myvar1, myvar2)
is equal to "col2 == 'A A' & col3 == 'B B'"
How one can deal with house in column identify
Let’s rename column col2
by together with an area in between for illustration function.
df.rename(columns={'col2':'col 2'}, inplace = True)
By utilizing backticks ``
you may cross a column which accommodates house.
myvar1 = '`col 2`' newdf = df.question("{0} == 'A A'".format(myvar1))
Associated Posts