0

Based on this qs from stackoverflow: SQL where in clause using column in pandas dataframe

I tried:

import pandas as pd

df1 = pd.DataFrame()
df1['col1'] = [1,2,3,4,5]

str = ','.join([str(x) for x in df1['col1'].unique().tolist()])

However, I see the below error:

TypeError: 'list' object is not callable

I want to query all the unique items in a column into another SQL table and then append those results to my original dataframe

is there another built-in approach altogether for this pls?

thanks

1 Answer 1

0

Maybe something like:

df1['new'] = df1['col1'].apply(lambda x: f(x) if x in df1['col1'].unique().tolist() else 'n/a')

You'll need to define f(x) to take in the unique value, run the query, and return the results you want to append. You can also change 'n/a' to whatever you want if it is not a unique value.

def f(x):
    "RUN QUERY HERE"
    return result
Sign up to request clarification or add additional context in comments.

5 Comments

thanks vm - I would still need to understand how lamda works and then how should my def f(x) look like.. if you will, could you help how I could use the query in the format qry = "Select id, SUM(revenue) AS revenue WHERE id IN (%s) Group by 1" % str apols - newb here, anmd I didn't quite follow all elements in your response (which may be the best way to do it) guess am just asking for a simpler answer...?
So are you just trying to add a new column by doing a lookup from an sql table?
No I want to make a query into an sql table.. The query statement uses all the unique elements of a column in my DF. The composition of this column will keep changing hence want to be able to put it in a variable which can be accessed via my query statement.. Just like str in the above example
Can you post what versions of python/pandas you are using? That str = ','.join.... line works fine for me
Python is 3.4.. Pandas might be pretty recent as I updated a week ago if I remember correctly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.