Search code examples
pythonpandasdataframepandas-datareaderpandasql

How to write sql query in pandas dataframe


How to write the below query in pandas data frame

SELECT * FROM Table
WHERE a = "S"
AND b IS NOT NULL
AND c IS NOT NULL;

Solution

  • If you're looking for an equivalent command to get the same result in a pandas dataframe, you can try this

    df = pd.DataFrame({'a':['S','T','S'],'b':[None, 1, 2],'c':[1,2,3]})
    df = df.dropna(subset=['b','c'])
    df.loc[df.dropna(subset=['b','c'])['a'] == 'S']
    

    Original dataframe

       a    b  c
    0  S  NaN  1
    1  T  1.0  2
    2  S  2.0  3
    

    Output

        a   b   c
    2   S   2.0 3