Johnsonge
Johnsonge

Reputation: 39

Using user input variables in PandaSQL

I'm trying to use pandaSQL on a dataframe that I have and I'm wondering if there's a way to use variables or if there's another way to do it. What I'm trying to do is setting user input as a variable and then trying to use that in the SQL statement. I want to display every instance that a shape when input. I'm trying stuff along the lines of:

variable1 = input("Enter shape here: ")
print pysqldf("SELECT imageNum FROM df WHERE shape1 = variable1 ")

but so far no luck. Everything else is working fine, I'm just running into trouble when introducing variables. Is this possible in pandaSQL and if not, what workarounds could I use?

Upvotes: 1

Views: 2482

Answers (1)

toto
toto

Reputation: 26

You'll need to pass the WHERE clause in the SQL query an argument in blockquotes, i.e.:

SELECT imageNum FROM df WHERE shape1 = "square".

So you'll need to pass a string that includes the quotation marks. Try the following:

variable1 = input("Enter shape here: ")

variable1str = "\"" + variable1 +"\""

print pysqldf("SELECT imageNum FROM df WHERE shape1 = variable1str ")

This way, if your input is, say, "square":

print variable1
`> square

print variable1str
'> "square"

Upvotes: 1

Related Questions