Friday, April 19, 2024
HomePythonHow one can use variable in a question in pandas

How one can use variable in a question in pandas


Suppose you wish to reference a variable in a question in pandas package deal in Python. This appears to be a simple job nevertheless it turns into daunting generally. Let’s focus on it with examples within the article beneath.

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 @.

Point out Worth Explicitly

newdf = df.question("col2 == 'A A'")
Reference Methodology

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

About Creator:

Deepanshu based ListenData with a easy goal – Make analytics straightforward to grasp and observe. He has over 10 years of expertise in information science. Throughout his tenure, he has labored with world shoppers in varied domains like Banking, Insurance coverage, Personal Fairness, Telecom and Human Useful resource.



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments