Since many potential pandas users have some familiarity with
SQL, this page is meant to provide some examples of how
various SQL operations would be performed using pandas.
If you’re new to pandas, you might want to first read through 10 Minutes to pandas
to familiarize yourself with the library.
As is customary, we import pandas and NumPy as follows:
In [1]: importpandasaspdIn [2]: importnumpyasnp
Most of the examples will utilize the dataset found within pandas tests. We’ll read
the data into a DataFrame called and assume we have a database table of the same name and
structure.
tips
tips
In [3]: url=( ...: "https://raw.githubusercontent.com/pandas-dev" ...: "/pandas/main/pandas/tests/io/data/csv/tips.csv" ...: ) ...: In [4]: tips=pd.read_csv(url)In [5]: tipsOut[5]: total_bill tip sex smoker day time size0 16.99 1.01 Female No Sun Dinner 21 10.34 1.66 Male No Sun Dinner 32 21.01 3.50 Male No Sun Dinner 33 23.68 3.31 Male No Sun Dinner 24 24.59 3.61 Female No Sun Dinner 4.. ... ... ... ... ... ... ...239 29.03 5.92 Male No Sat Dinner 3240 27.18 2.00 Female Yes Sat Dinner 2241 22.67 2.00 Male Yes Sat Dinner 2242 17.82 1.75 Male No Sat Dinner 2243 18.78 3.00 Female No Thur Dinner 2[244 rows x 7 columns]
Copies vs. in place operations
Most pandas operations return copies of the Series/DataFrame. To make the changes “stick”,
you’ll need to either assign to a new variable:
sorted_df=df.sort_values("col1")
or overwrite the original one:
df=df.sort_values("col1")
SELECT
In SQL, selection is done using a comma-separated list of columns you’d like to select (or a *
to select all columns):
SELECTtotal_bill,tip,smoker,timeFROMtips;
With pandas, column selection is done by passing a list of column names to your DataFrame:
In [6]: tips[["total_bill","tip","smoker","time"]]Out[6]: total_bill tip smoker time0 16.99 1.01 No Dinner1 10.34 1.66 No Dinner2 21.01 3.50 No Dinner3 23.68 3.31 No Dinner4 24.59 3.61 No Dinner.. ... ... ... ...239 29.03 5.92 No Dinner240 27.18 2.00 Yes Dinner241 22.67 2.00 Yes Dinner242 17.82 1.75 No Dinner243 18.78 3.00 No Dinner[244 rows x 4 columns]
Calling the DataFrame without the list of column names would display all columns (akin to SQL’s
*).
In SQL, you can add a calculated column:
SELECT*,tip/total_billastip_rateFROMtips;
With pandas, you can use the DataFrame.assign() method of a DataFrame to append a new column:
In [7]: tips.assign(tip_rate=tips["tip"]/tips["total_bill"])Out[7]: total_bill tip sex smoker day time size tip_rate0 16.99 1.01 Female No Sun Dinner 2 0.0594471 10.34 1.66 Male No Sun Dinner 3 0.1605422 21.01 3.50 Male No Sun Dinner 3 0.1665873 23.68 3.31 Male No Sun Dinner 2 0.1397804 24.59 3.61 Female No Sun Dinner 4 0.146808.. ... ... ... ... ... ... ... ...239 29.03 5.92 Male No Sat Dinner 3 0.203927240 27.18 2.00 Female Yes Sat Dinner 2 0.073584241 22.67 2.00 Male Yes Sat Dinner 2 0.088222242 17.82 1.75 Male No Sat Dinner 2 0.098204
WHERE
Filtering in SQL is done via a WHERE clause.
SELECT*FROMtipsWHEREtime='Dinner';
DataFrames can be filtered in multiple ways; the most intuitive of which is using
boolean indexing.
In [8]: tips[tips["total_bill"]>10]Out[8]: total_bill tip sex smoker day time size0 16.99 1.01 Female No Sun Dinner 21 10.34 1.66 Male No Sun Dinner 32 21.01 3.50 Male No Sun Dinner 33 23.68 3.31 Male No Sun Dinner 24 24.59 3.61 Female No Sun Dinner 4.. ... ... ... ... ... ... ...239 29.03 5.92 Male No Sat Dinner 3240 27.18 2.00 Female Yes Sat Dinner 2241 22.67 2.00 Male Yes Sat Dinner 2242 17.82 1.75 Male No Sat Dinner 2243 18.78 3.00 Female No Thur Dinner 2[227 rows x 7 columns]
The above statement is simply passing a Series of True/False objects to the DataFrame,
returning all rows with True.
Just like SQL’s OR and AND, multiple conditions can be passed to a DataFrame using |
(OR) and & (AND).
Tips of more than $5 at Dinner meals:
SELECT*FROMtipsWHEREtime='Dinner'ANDtip>5.00;
In [13]: tips[(tips["time"]=="Dinner")&(tips["tip"]>5.00)]Out[13]: total_bill tip sex smoker day time size23 39.42 7.58 Male No Sat Dinner 444 30.40 5.60 Male No Sun Dinner 447 32.40 6.00 Male No Sun Dinner 452 34.81 5.20 Female No Sun Dinner 459 48.27 6.73 Male No Sat Dinner 4116 29.93 5.07 Male No Sun Dinner 4155 29.85 5.14 Female No Sun Dinner 5170 50.81 10.00 Male Yes Sat Dinner 3172 7.25 5.15 Male Yes Sun Dinner 2
Tips by parties of at least 5 diners OR bill total was more than $45:
SELECT*FROMtipsWHEREsize>=5ORtotal_bill>45;
In [14]: tips[(tips["size"]>=5)|(tips["total_bill"]>45)]Out[14]: total_bill tip sex smoker day time size59 48.27 6.73 Male No Sat Dinner 4125 29.80 4.20 Female No Thur Lunch 6141 34.30 6.70 Male No Thur Lunch 6142 41.19 5.00 Male No Thur Lunch 5143 27.05 5.00 Female No Thur Lunch 6155 29.85 5.14 Female No Sun Dinner 5156 48.17 5.00 Male No Sun Dinner 6170 50.81 10.00 Male Yes Sat Dinner 3182 45.35 3.50 Male Yes Sun Dinner 3
NULL checking is done using the notna() and isna()
methods.
In [15]: frame=pd.DataFrame( ....: {"col1":["A","B",np.nan,"C","D"],"col2":["F",np.nan,"G","H","I"
Assume we have a table of the same structure as our DataFrame above. We can see only the records
where col2 IS NULL with the following query:
SELECT*FROMframeWHEREcol2ISNULL;
In [17]: frame[frame["col2"].isna()]Out[17]: col1 col21 B NaN
Getting items where col1 IS NOT NULL can be done with notna().
SELECT*FROMframeWHEREcol1ISNOTNULL;
In [18]: frame[frame["col1"].notna()]Out[18]: col1 col20 A F1 B NaN3 C H4 D I
GROUP BY
In pandas, SQL’s GROUPBY operations are performed using the similarly named
groupby() method. groupby() typically refers to a
process where we’d like to split a dataset into groups, apply some function (typically aggregation)
, and then combine the groups together.
A common SQL operation would be getting the count of records in each group throughout a dataset.
For instance, a query getting us the number of tips left by sex:
In [20]: tips.groupby("sex").count()Out[20]: total_bill tip smoker day time sizesex Female 87 87 87 87 87 87Male 157 157 157 157 157 157
Alternatively, we could have applied the DataFrameGroupBy.count() method
to an individual column:
In [21]: tips.groupby("sex")["total_bill"].count()Out[21]: sexFemale 87Male 157Name: total_bill, dtype: int64
Multiple functions can also be applied at once. For instance, say we’d like to see how tip amount
differs by day of the week - DataFrameGroupBy.agg() allows you to pass a dictionary
to your grouped DataFrame, indicating which functions to apply to specific columns.
In [22]: tips.groupby("day").agg({"tip":"mean","day":"size"})Out[22]: tip dayday Fri 2.734737 19Sat 2.993103 87Sun 3.255132 76Thur 2.771452 62
Grouping by more than one column is done by passing a list of columns to the
groupby() method.
SELECTsmoker,day,COUNT(*),AVG(tip)FROMtipsGROUPBYsmoker,day;/*smoker dayNo Fri 4 2.812500 Sat 45 3.102889 Sun 57 3.167895 Thu 45 2.673778Yes Fri 15 2.714000 Sat 42 2.875476
In [23]: tips.groupby(["smoker","day"]).agg({"tip":["size","mean"]})Out[23]: tip size meansmoker day No Fri 4 2.812500 Sat 45 3.102889 Sun 57 3.167895 Thur 45 2.673778Yes Fri 15 2.714000 Sat 42 2.875476 Sun 19 3.516842 Thur 17 3.030000
JOIN
JOINs can be performed with join() or merge(). By
default, join() will join the DataFrames on their indices. Each method has
parameters allowing you to specify the type of join to perform (LEFT, RIGHT, INNER,
FULL) or the columns to join on (column names or indices).
In [24]: df1=pd.DataFrame({"key":["A","B","C","D"],"value":np.random.randn(4)})In [25]: df2=pd.DataFrame({"key":["B"
Assume we have two database tables of the same name and structure as our DataFrames.
Now let’s go over the various types of JOINs.
INNER JOIN
SELECT*FROMdf1INNERJOINdf2ONdf1.key=df2.key;
# merge performs an INNER JOIN by defaultIn [26]: pd.
LEFT OUTER JOIN
Show all records from df1.
SELECT*FROMdf1LEFTOUTERJOINdf2ONdf1.key=df2.key;
RIGHT JOIN
Show all records from df2.
SELECT*FROMdf1RIGHTOUTERJOINdf2ONdf1.key=df2.key;
FULL JOIN
pandas also allows for FULLJOINs, which display both sides of the dataset, whether or not the
joined columns find a match. As of writing, FULLJOINs are not supported in all RDBMS (MySQL).
In [32]: df1=pd.DataFrame( ....: {"city":["Chicago","San Francisco","New York City"],"rank":range(1,4)} ....: ) ....: In [33]: df2=pd.DataFrame( ....: {"city":["Chicago","Boston","Los Angeles"],"rank":[1,4,5]} ....: ) ....:
SELECTcity,rankFROMdf1UNIONALLSELECTcity,rankFROMdf2;/* city rank Chicago 1San Francisco 2New York City 3 Chicago 1 Boston 4 Los Angeles 5*/
In [34]: pd.concat([df1,df2])Out[34]: city rank0 Chicago 11 San Francisco 22 New York City 30 Chicago 11 Boston 42 Los Angeles 5
SQL’s UNION is similar to UNIONALL, however UNION will remove duplicate rows.
SELECTcity,rankFROMdf1UNIONSELECTcity,rankFROMdf2;-- notice that there is only one Chicago record this time/* city rank Chicago 1San Francisco 2New York City 3 Boston 4 Los Angeles 5*/
In [35]: pd.concat([df1,df2]).drop_duplicates()Out[35]: city rank0 Chicago 11 San Francisco 22 New York City 31 Boston 42 Los Angeles 5
LIMIT
SELECT*FROMtipsLIMIT10;
In [36]: tips.head(10)Out[36]: total_bill tip sex smoker day time size0 16.99 1.01 Female No Sun Dinner 21 10.34 1.66 Male No Sun Dinner 32 21.01 3.50 Male No Sun Dinner 33 23.68 3.31 Male No Sun Dinner 24 24.59 3.61 Female No Sun Dinner 45 25.29 4.71 Male No Sun Dinner 46 8.77 2.00 Male No Sun Dinner 27 26.88 3.12 Male No Sun Dinner 48 15.04 1.96 Male No Sun Dinner 29 14.78 3.23 Male No Sun Dinner 2
pandas equivalents for some SQL analytic and aggregate functions
In [37]: tips.nlargest(10+5,columns="tip").tail(10)Out[37]: total_bill tip sex smoker day time size183 23.17 6.50 Male Yes Sun Dinner 4214 28.17 6.50 Female Yes Sat Dinner 347 32.40 6.00 Male No Sun Dinner 4239 29.03 5.92 Male No Sat Dinner 388 24.71 5.85 Male No Thur Lunch 2181 23.33 5.65 Male Yes Sun Dinner 244 30.40 5.60 Male No Sun Dinner 452 34.81 5.20 Female No Sun Dinner 485 34.83 5.17 Female No Thur Lunch 4211 25.89 5.16 Male Yes Sat Dinner 4
merge() also offers parameters for cases when you’d like to join one DataFrame’s
column with another DataFrame’s index.
In [27]: indexed_df2=df2.set_index("key")In [28]: pd.merge(df1,indexed_df2,left_on="key",right_index=True)Out[28]: key value_x value_y1 B -0.282863 1.2121123 D -1.135632 -0.1732153 D -1.135632 0.119209
In [29]: pd.merge(df1,df2,on="key",how="left")Out[29]: key value_x value_y0 A 0.469112 NaN1 B -0.282863 1.2121122 C -1.509059 NaN3 D -1.135632 -0.1732154 D -1.135632 0.119209
In [30]: pd.merge(df1,df2,on="key",how="right")Out[30]: key value_x value_y0 B -0.282863 1.2121121 D -1.135632 -0.1732152 D -1.135632 0.1192093 E NaN -1.044236
;
In [31]: pd.merge(df1,df2,on="key",how="outer")Out[31]: key value_x value_y0 A 0.469112 NaN1 B -0.282863 1.2121122 C -1.509059 NaN3 D -1.135632 -0.1732154 D -1.135632 0.1192095 E NaN -1.044236
FROM
tips
t
)
WHERE
rn
<
3
ORDER
BY
day
,
rn
;
In [38]: ( ....: tips.assign( ....: rn=tips.sort_values(["total_bill"],ascending=False) ....: .groupby(["day"]) ....: .cumcount() ....: +1 ....: ) ....: .query("rn < 3") ....: .sort_values(["day","rn"]) ....: ) ....: Out[38]: total_bill tip sex smoker day time size rn95 40.17 4.73 Male Yes Fri Dinner 4 190 28.97 3.00 Male Yes Fri Dinner 2 2170 50.81 10.00 Male Yes Sat Dinner 3 1212 48.33 9.00 Male No Sat Dinner 4 2156 48.17 5.00 Male No Sun Dinner 6 1182 45.35 3.50 Male Yes Sun Dinner 3 2197 43.11 5.00 Female Yes Thur Lunch 4 1142 41.19 5.00 Male No Thur Lunch 5 2
the same using rank(method='first') function
In [39]: ( ....: tips.assign( ....: rnk=tips.groupby(["day"])["total_bill"].rank( ....: method="first",ascending=False ....: ) ....: ) ....: .query("rnk < 3") ....: .sort_values(["day","rnk"]) ....: ) ....: Out[39]: total_bill tip sex smoker day time size rnk95 40.17 4.73 Male Yes Fri Dinner 4 1.090 28.97 3.00 Male Yes Fri Dinner 2 2.0170 50.81 10.00 Male Yes Sat Dinner 3 1.0212 48.33 9.00 Male No Sat Dinner 4 2.0156 48.17 5.00 Male No Sun Dinner 6 1.0182 45.35 3.50 Male Yes Sun Dinner 3 2.0197 43.11 5.00 Female Yes Thur Lunch 4 1.0142 41.19 5.00 Male No Thur Lunch 5 2.0
Let’s find tips with (rank < 3) per gender group for (tips < 2).
Notice that when using rank(method='min') function
rnk_min remains the same for the same tip
(as Oracle’s RANK() function)
In [40]: ( ....: tips[tips["tip"]<2] ....: .assign(rnk_min=tips.groupby(["sex"])["tip"].rank(method="min")) ....: .query("rnk_min < 3") ....: .sort_values(["sex","rnk_min"]) ....: ) ....: Out[40]: total_bill tip sex smoker day time size rnk_min67 3.07 1.00 Female Yes Sat Dinner 1 1.092 5.75 1.00 Female Yes Fri Dinner 2 1.0111 7.25 1.00 Female No Sat Dinner 1 1.0236 12.60 1.00 Male Yes Sat Dinner 2 1.0237 32.83 1.17 Male Yes Sat Dinner 2 2.0