Author

Tony Duan

This document provides a comprehensive guide to performing common data manipulation tasks using SQL, R, and Python. It serves as a reference for understanding how to achieve similar outcomes across these three popular data analysis tools.

1 Setup and Configuration

Code
library(reticulate)
py_require(c("pandas","Great-Tables","polars","pyarrow"))

# Load libraries for database interaction, data manipulation, and connections.
library(DBI)
library(tidyverse)
library(RSQLite)
library(connections)
library(duckdb)

# Prepare the R dataframes.
# Remove the existing mtcars dataset if it exists.
rm(mtcars)
# Create the mtcars dataframe from the base R dataset, adding the row names as a new column.
mtcars = cbind(model_name = rownames(mtcars), mtcars) |> head(10)
# Create the iris dataframe from the base R dataset.
iris = iris |> head(10)

# Remove the database file if it already exists to start with a clean slate.
if (file.exists("my-db.duckdb")) {
  file.remove("my-db.duckdb")
}
# Establish a connection to the DuckDB database.
con <- dbConnect(duckdb(), dbdir = "my-db.duckdb", read_only = FALSE)
# Write the iris and mtcars dataframes to the database as tables.
dbWriteTable(con, "iris_table", iris, overwrite = TRUE)
dbWriteTable(con, "mtcars_table", mtcars, overwrite = TRUE)
Code
import pandas as pd
import polars as pl
import os

from platform import python_version
#print(python_version())

cities_pd = pd.DataFrame({
    'country': ['NL', 'NL', 'NL', 'US', 'US', 'US', 'US', 'US', 'US'],
    'name': ['Amsterdam', 'Amsterdam', 'Amsterdam', 'Seattle', 'Seattle', 'Seattle', 'New York City', 'New York City', 'New York City'],
    'year': [2000, 2010, 2020, 2000, 2010, 2020, 2000, 2010, 2020],
    'population': [1005, 1065, 1158, 564, 608, 738, 8015, 8175, 8772]
})

# Make the R dataframes available in the Python environment.
mtcars_pd = r.mtcars
iris_pd = r.iris
mtcars_pl = pl.from_pandas(mtcars_pd)
iris_pl = pl.from_pandas(iris_pd)
cities_pl=pl.from_pandas(cities_pd)
  • There are tables iris_table and mtcars_table in the DuckDB database my-db.duckdb.
  • There are dataframes iris and mtcars in the R environment.
  • There are dataframes iris and mtcars in the Python environment.

2 Show All Tables

This section demonstrates how to list all available tables or dataframes in each environment.

Code
-- Show all tables in the connected database.
SHOW ALL TABLES;
2 records
database schema name column_names column_types temporary
my-db main iris_table Sepal.Length, Sepal.Width , Petal.Length, Petal.Width , Species DOUBLE , DOUBLE , DOUBLE , DOUBLE , ENUM(‘setosa’, ‘versicolor’, ‘virginica’) FALSE
my-db main mtcars_table model_name, mpg , cyl , disp , hp , drat , wt , qsec , vs , am , gear , carb VARCHAR, DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE FALSE
Code
# List all dataframes in the current R environment.
dflist <- Filter(is.data.frame, as.list(.GlobalEnv))
names(dflist)
[1] "mtcars" "iris"  
Code
# List all pandas dataframes in the current Python environment.
import pandas as pd
alldfs = [var for var in dir() if isinstance(eval(var), pd.core.frame.DataFrame)]
print(alldfs)
['cities_pd', 'iris_pd', 'mtcars_pd']
Code
import polars as pl

alldfs = [name for name, val in globals().items() if isinstance(val, pl.DataFrame)]
print(alldfs)
['mtcars_pl', 'iris_pl', 'cities_pl']

3 Describe a Table

This section shows how to get a summary of a table’s structure and statistics.

Code
-- Describe the columns and data types of the mtcars_table.
DESCRIBE mtcars_table;
Displaying records 1 - 10
column_name column_type null key default extra
model_name VARCHAR YES NA NA NA
mpg DOUBLE YES NA NA NA
cyl DOUBLE YES NA NA NA
disp DOUBLE YES NA NA NA
hp DOUBLE YES NA NA NA
drat DOUBLE YES NA NA NA
wt DOUBLE YES NA NA NA
qsec DOUBLE YES NA NA NA
vs DOUBLE YES NA NA NA
am DOUBLE YES NA NA NA
Code
# Provide a detailed summary of the mtcars dataframe.
skimr::skim(mtcars)
Data summary
Name mtcars
Number of rows 10
Number of columns 12
_______________________
Column type frequency:
character 1
numeric 11
________________________
Group variables None

Variable type: character

skim_variable n_missing complete_rate min max empty n_unique whitespace
model_name 0 1 7 17 0 10 0

Variable type: numeric

skim_variable n_missing complete_rate mean sd p0 p25 p50 p75 p100 hist
mpg 0 1 20.37 2.91 14.30 18.82 21.00 22.45 24.40 ▂▂▅▇▇
cyl 0 1 5.80 1.48 4.00 4.50 6.00 6.00 8.00 ▅▁▇▁▃
disp 0 1 208.61 90.37 108.00 150.02 163.80 249.75 360.00 ▇▇▅▁▅
hp 0 1 122.80 51.45 62.00 97.50 110.00 119.75 245.00 ▅▇▁▂▂
drat 0 1 3.54 0.44 2.76 3.16 3.77 3.90 3.92 ▁▃▁▁▇
wt 0 1 3.13 0.41 2.32 2.94 3.20 3.44 3.57 ▂▂▂▆▇
qsec 0 1 18.58 2.14 15.84 17.02 18.45 19.86 22.90 ▇▃▃▂▂
vs 0 1 0.60 0.52 0.00 0.00 1.00 1.00 1.00 ▅▁▁▁▇
am 0 1 0.30 0.48 0.00 0.00 0.00 0.75 1.00 ▇▁▁▁▃
gear 0 1 3.60 0.52 3.00 3.00 4.00 4.00 4.00 ▅▁▁▁▇
carb 0 1 2.50 1.35 1.00 1.25 2.00 4.00 4.00 ▆▆▁▁▇
Code
# Generate descriptive statistics for the mtcars dataframe.
mtcars_pd.describe(include='all')
       model_name        mpg       cyl  ...         am       gear       carb
count          10  10.000000  10.00000  ...  10.000000  10.000000  10.000000
unique         10        NaN       NaN  ...        NaN        NaN        NaN
top     Mazda RX4        NaN       NaN  ...        NaN        NaN        NaN
freq            1        NaN       NaN  ...        NaN        NaN        NaN
mean          NaN  20.370000   5.80000  ...   0.300000   3.600000   2.500000
std           NaN   2.907099   1.47573  ...   0.483046   0.516398   1.354006
min           NaN  14.300000   4.00000  ...   0.000000   3.000000   1.000000
25%           NaN  18.825000   4.50000  ...   0.000000   3.000000   1.250000
50%           NaN  21.000000   6.00000  ...   0.000000   4.000000   2.000000
75%           NaN  22.450000   6.00000  ...   0.750000   4.000000   4.000000
max           NaN  24.400000   8.00000  ...   1.000000   4.000000   4.000000

[11 rows x 12 columns]
Code
mtcars_pl.describe()
shape: (9, 13)
statistic model_name mpg cyl disp hp drat wt qsec vs am gear carb
str str f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64
"count" "10" 10.0 10.0 10.0 10.0 10.0 10.0 10.0 10.0 10.0 10.0 10.0
"null_count" "0" 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
"mean" null 20.37 5.8 208.61 122.8 3.538 3.128 18.581 0.6 0.3 3.6 2.5
"std" null 2.907099 1.47573 90.373896 51.449652 0.440651 0.40649 2.135845 0.516398 0.483046 0.516398 1.354006
"min" "Datsun 710" 14.3 4.0 108.0 62.0 2.76 2.32 15.84 0.0 0.0 3.0 1.0
"25%" null 18.7 4.0 146.7 95.0 3.15 2.875 17.02 0.0 0.0 3.0 1.0
"50%" null 21.0 6.0 167.6 110.0 3.85 3.215 18.61 1.0 0.0 4.0 2.0
"75%" null 22.8 6.0 258.0 123.0 3.9 3.44 20.0 1.0 1.0 4.0 4.0
"max" "Valiant" 24.4 8.0 360.0 245.0 3.92 3.57 22.9 1.0 1.0 4.0 4.0

4 Show Column Names

This section demonstrates how to retrieve the column names of a table.

Code
-- Show information about the columns in mtcars_table.
PRAGMA table_info(mtcars_table);
Displaying records 1 - 10
cid name type notnull dflt_value pk
0 model_name VARCHAR FALSE NA FALSE
1 mpg DOUBLE FALSE NA FALSE
2 cyl DOUBLE FALSE NA FALSE
3 disp DOUBLE FALSE NA FALSE
4 hp DOUBLE FALSE NA FALSE
5 drat DOUBLE FALSE NA FALSE
6 wt DOUBLE FALSE NA FALSE
7 qsec DOUBLE FALSE NA FALSE
8 vs DOUBLE FALSE NA FALSE
9 am DOUBLE FALSE NA FALSE
Code
# Get the names of the columns in the mtcars dataframe.
names(mtcars)
 [1] "model_name" "mpg"        "cyl"        "disp"       "hp"        
 [6] "drat"       "wt"         "qsec"       "vs"         "am"        
[11] "gear"       "carb"      
Code
# Get a list of column names from the mtcars dataframe.
import pandas as pd
list(mtcars_pd.columns.values)
['model_name', 'mpg', 'cyl', 'disp', 'hp', 'drat', 'wt', 'qsec', 'vs', 'am', 'gear', 'carb']
Code
# Get a list of column names from the mtcars dataframe.
mtcars_pl.columns
['model_name', 'mpg', 'cyl', 'disp', 'hp', 'drat', 'wt', 'qsec', 'vs', 'am', 'gear', 'carb']

5 Select

5.1 Select Top 6 and Rename

This section shows how to select a subset of columns, rename them, and limit the number of rows returned.

Code
-- Select and rename columns, limiting the result to the top 6 rows.
SELECT model_name as model, mpg, cyl FROM mtcars_table LIMIT 6;
6 records
model mpg cyl
Mazda RX4 21.0 6
Mazda RX4 Wag 21.0 6
Datsun 710 22.8 4
Hornet 4 Drive 21.4 6
Hornet Sportabout 18.7 8
Valiant 18.1 6
Code
# Select and rename columns from the first 6 rows of the mtcars dataframe.
head(mtcars, 6) |> select(model = model_name, mpg, cyl)
                              model  mpg cyl
Mazda RX4                 Mazda RX4 21.0   6
Mazda RX4 Wag         Mazda RX4 Wag 21.0   6
Datsun 710               Datsun 710 22.8   4
Hornet 4 Drive       Hornet 4 Drive 21.4   6
Hornet Sportabout Hornet Sportabout 18.7   8
Valiant                     Valiant 18.1   6
Code
# Rename a column in the mtcars dataframe.
mtcars_pd.rename(columns={'model_name': 'model'})
                               model   mpg  cyl   disp  ...   vs   am  gear  carb
Mazda RX4                  Mazda RX4  21.0  6.0  160.0  ...  0.0  1.0   4.0   4.0
Mazda RX4 Wag          Mazda RX4 Wag  21.0  6.0  160.0  ...  0.0  1.0   4.0   4.0
Datsun 710                Datsun 710  22.8  4.0  108.0  ...  1.0  1.0   4.0   1.0
Hornet 4 Drive        Hornet 4 Drive  21.4  6.0  258.0  ...  1.0  0.0   3.0   1.0
Hornet Sportabout  Hornet Sportabout  18.7  8.0  360.0  ...  0.0  0.0   3.0   2.0
Valiant                      Valiant  18.1  6.0  225.0  ...  1.0  0.0   3.0   1.0
Duster 360                Duster 360  14.3  8.0  360.0  ...  0.0  0.0   3.0   4.0
Merc 240D                  Merc 240D  24.4  4.0  146.7  ...  1.0  0.0   4.0   2.0
Merc 230                    Merc 230  22.8  4.0  140.8  ...  1.0  0.0   4.0   2.0
Merc 280                    Merc 280  19.2  6.0  167.6  ...  1.0  0.0   4.0   4.0

[10 rows x 12 columns]
Code
mtcars_pl.select(pl.col("model_name").alias("model"), pl.col("mpg"), pl.col("cyl")).head(6)
shape: (6, 3)
model mpg cyl
str f64 f64
"Mazda RX4" 21.0 6.0
"Mazda RX4 Wag" 21.0 6.0
"Datsun 710" 22.8 4.0
"Hornet 4 Drive" 21.4 6.0
"Hornet Sportabout" 18.7 8.0
"Valiant" 18.1 6.0

5.2 Select Distinct

This section demonstrates how to retrieve unique rows based on specified columns.

Code
-- Select distinct combinations of mpg and cyl.
SELECT DISTINCT mpg, cyl FROM mtcars_table;
8 records
mpg cyl
22.8 4
18.1 6
14.3 8
21.0 6
21.4 6
24.4 4
19.2 6
18.7 8
Code
# Get distinct rows based on mpg and cyl.
mtcars |> distinct(mpg, cyl)
                   mpg cyl
Mazda RX4         21.0   6
Datsun 710        22.8   4
Hornet 4 Drive    21.4   6
Hornet Sportabout 18.7   8
Valiant           18.1   6
Duster 360        14.3   8
Merc 240D         24.4   4
Merc 280          19.2   6
Code
# Select specific columns and drop duplicate rows.
df = mtcars_pd[["mpg", "cyl"]]
print(df.drop_duplicates())
                    mpg  cyl
Mazda RX4          21.0  6.0
Datsun 710         22.8  4.0
Hornet 4 Drive     21.4  6.0
Hornet Sportabout  18.7  8.0
Valiant            18.1  6.0
Duster 360         14.3  8.0
Merc 240D          24.4  4.0
Merc 280           19.2  6.0
Code
mtcars_pl.select(pl.col("mpg"), pl.col("cyl")).unique()
shape: (8, 2)
mpg cyl
f64 f64
18.7 8.0
14.3 8.0
19.2 6.0
24.4 4.0
18.1 6.0
21.4 6.0
22.8 4.0
21.0 6.0

6 Check Row and Column Number

This section shows how to find the dimensions of a table.

Code
-- Get the total number of rows.
SELECT count(*) AS row_number FROM mtcars_table;
1 records
row_number
10
Code
-- Get the total number of columns.
SELECT count(*) AS column_number FROM (DESCRIBE mtcars_table);
1 records
column_number
12
Code
# Get the number of rows.
nrow(mtcars)
[1] 10
Code
# Get the number of columns.
ncol(mtcars)
[1] 12
Code
# Get the number of rows.
mtcars_pd.shape[0]
10
Code
# Get the number of columns.
mtcars_pd.shape[1]
12
Code
# Get the number of rows.
mtcars_pl.shape[0]
10
Code
# Get the number of columns.
mtcars_pl.shape[1]
12

7 Create Column

This section demonstrates how to add a new column to a table based on existing data.

Code
-- Create a new column by performing a calculation on an existing column.
SELECT *, mpg + 1 AS new_mpg FROM mtcars_table;
Displaying records 1 - 10
model_name mpg cyl disp hp drat wt qsec vs am gear carb new_mpg
Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 22.0
Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 22.0
Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 23.8
Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 22.4
Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2 19.7
Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1 19.1
Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4 15.3
Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2 25.4
Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2 23.8
Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4 20.2
Code
# Add a new column to the dataframe.
mtcars |> mutate(new_mpg = mpg + 1)
                         model_name  mpg cyl  disp  hp drat    wt  qsec vs am
Mazda RX4                 Mazda RX4 21.0   6 160.0 110 3.90 2.620 16.46  0  1
Mazda RX4 Wag         Mazda RX4 Wag 21.0   6 160.0 110 3.90 2.875 17.02  0  1
Datsun 710               Datsun 710 22.8   4 108.0  93 3.85 2.320 18.61  1  1
Hornet 4 Drive       Hornet 4 Drive 21.4   6 258.0 110 3.08 3.215 19.44  1  0
Hornet Sportabout Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0
Valiant                     Valiant 18.1   6 225.0 105 2.76 3.460 20.22  1  0
Duster 360               Duster 360 14.3   8 360.0 245 3.21 3.570 15.84  0  0
Merc 240D                 Merc 240D 24.4   4 146.7  62 3.69 3.190 20.00  1  0
Merc 230                   Merc 230 22.8   4 140.8  95 3.92 3.150 22.90  1  0
Merc 280                   Merc 280 19.2   6 167.6 123 3.92 3.440 18.30  1  0
                  gear carb new_mpg
Mazda RX4            4    4    22.0
Mazda RX4 Wag        4    4    22.0
Datsun 710           4    1    23.8
Hornet 4 Drive       3    1    22.4
Hornet Sportabout    3    2    19.7
Valiant              3    1    19.1
Duster 360           3    4    15.3
Merc 240D            4    2    25.4
Merc 230             4    2    23.8
Merc 280             4    4    20.2
Code
# Create a new column in the dataframe.
mtcars_pd["new_mpg"] = mtcars_pd["mpg"] + 1
mtcars_pd
                          model_name   mpg  cyl  ...  gear  carb  new_mpg
Mazda RX4                  Mazda RX4  21.0  6.0  ...   4.0   4.0     22.0
Mazda RX4 Wag          Mazda RX4 Wag  21.0  6.0  ...   4.0   4.0     22.0
Datsun 710                Datsun 710  22.8  4.0  ...   4.0   1.0     23.8
Hornet 4 Drive        Hornet 4 Drive  21.4  6.0  ...   3.0   1.0     22.4
Hornet Sportabout  Hornet Sportabout  18.7  8.0  ...   3.0   2.0     19.7
Valiant                      Valiant  18.1  6.0  ...   3.0   1.0     19.1
Duster 360                Duster 360  14.3  8.0  ...   3.0   4.0     15.3
Merc 240D                  Merc 240D  24.4  4.0  ...   4.0   2.0     25.4
Merc 230                    Merc 230  22.8  4.0  ...   4.0   2.0     23.8
Merc 280                    Merc 280  19.2  6.0  ...   4.0   4.0     20.2

[10 rows x 13 columns]
Code
mtcars_pl.with_columns((pl.col("mpg") + 1).alias("new_mpg"))
shape: (10, 13)
model_name mpg cyl disp hp drat wt qsec vs am gear carb new_mpg
str f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64
"Mazda RX4" 21.0 6.0 160.0 110.0 3.9 2.62 16.46 0.0 1.0 4.0 4.0 22.0
"Mazda RX4 Wag" 21.0 6.0 160.0 110.0 3.9 2.875 17.02 0.0 1.0 4.0 4.0 22.0
"Datsun 710" 22.8 4.0 108.0 93.0 3.85 2.32 18.61 1.0 1.0 4.0 1.0 23.8
"Hornet 4 Drive" 21.4 6.0 258.0 110.0 3.08 3.215 19.44 1.0 0.0 3.0 1.0 22.4
"Hornet Sportabout" 18.7 8.0 360.0 175.0 3.15 3.44 17.02 0.0 0.0 3.0 2.0 19.7
"Valiant" 18.1 6.0 225.0 105.0 2.76 3.46 20.22 1.0 0.0 3.0 1.0 19.1
"Duster 360" 14.3 8.0 360.0 245.0 3.21 3.57 15.84 0.0 0.0 3.0 4.0 15.3
"Merc 240D" 24.4 4.0 146.7 62.0 3.69 3.19 20.0 1.0 0.0 4.0 2.0 25.4
"Merc 230" 22.8 4.0 140.8 95.0 3.92 3.15 22.9 1.0 0.0 4.0 2.0 23.8
"Merc 280" 19.2 6.0 167.6 123.0 3.92 3.44 18.3 1.0 0.0 4.0 4.0 20.2

8 Filter

This section shows how to select rows that meet specific criteria.

Code
-- Use the AND operator to filter rows based on multiple conditions.
SELECT * FROM mtcars_table WHERE mpg = 21 AND cyl = 6;
2 records
model_name mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21 6 160 110 3.9 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21 6 160 110 3.9 2.875 17.02 0 1 4 4
Code
-- Use the OR operator to filter rows.
SELECT * FROM mtcars_table WHERE mpg = 21 OR cyl = 6;
5 records
model_name mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1
Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1
Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4
Code
# Use the & operator for "and" filtering.
mtcars |> filter(mpg == 21 & cyl == 6)
                 model_name mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         Mazda RX4  21   6  160 110  3.9 2.620 16.46  0  1    4    4
Mazda RX4 Wag Mazda RX4 Wag  21   6  160 110  3.9 2.875 17.02  0  1    4    4
Code
# Use the | operator for "or" filtering.
mtcars |> filter(mpg == 21 | cyl == 6)
                   model_name  mpg cyl  disp  hp drat    wt  qsec vs am gear
Mazda RX4           Mazda RX4 21.0   6 160.0 110 3.90 2.620 16.46  0  1    4
Mazda RX4 Wag   Mazda RX4 Wag 21.0   6 160.0 110 3.90 2.875 17.02  0  1    4
Hornet 4 Drive Hornet 4 Drive 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3
Valiant               Valiant 18.1   6 225.0 105 2.76 3.460 20.22  1  0    3
Merc 280             Merc 280 19.2   6 167.6 123 3.92 3.440 18.30  1  0    4
               carb
Mazda RX4         4
Mazda RX4 Wag     4
Hornet 4 Drive    1
Valiant           1
Merc 280          4
Code
# Use the query method for "and" filtering.
mtcars_pd.query('mpg == 21 and cyl == 6')
                  model_name   mpg  cyl   disp  ...   am  gear  carb  new_mpg
Mazda RX4          Mazda RX4  21.0  6.0  160.0  ...  1.0   4.0   4.0     22.0
Mazda RX4 Wag  Mazda RX4 Wag  21.0  6.0  160.0  ...  1.0   4.0   4.0     22.0

[2 rows x 13 columns]
Code
# Use the query method for "or" filtering.
mtcars_pd.query('mpg == 21 or cyl == 6')
                    model_name   mpg  cyl   disp  ...   am  gear  carb  new_mpg
Mazda RX4            Mazda RX4  21.0  6.0  160.0  ...  1.0   4.0   4.0     22.0
Mazda RX4 Wag    Mazda RX4 Wag  21.0  6.0  160.0  ...  1.0   4.0   4.0     22.0
Hornet 4 Drive  Hornet 4 Drive  21.4  6.0  258.0  ...  0.0   3.0   1.0     22.4
Valiant                Valiant  18.1  6.0  225.0  ...  0.0   3.0   1.0     19.1
Merc 280              Merc 280  19.2  6.0  167.6  ...  0.0   4.0   4.0     20.2

[5 rows x 13 columns]
Code
# "and" filtering with polars
mtcars_pl.filter((pl.col("mpg") == 21) & (pl.col("cyl") == 6))
shape: (2, 12)
model_name mpg cyl disp hp drat wt qsec vs am gear carb
str f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64
"Mazda RX4" 21.0 6.0 160.0 110.0 3.9 2.62 16.46 0.0 1.0 4.0 4.0
"Mazda RX4 Wag" 21.0 6.0 160.0 110.0 3.9 2.875 17.02 0.0 1.0 4.0 4.0
Code
# "or" filtering with polars
mtcars_pl.filter((pl.col("mpg") == 21) | (pl.col("cyl") == 6))
shape: (5, 12)
model_name mpg cyl disp hp drat wt qsec vs am gear carb
str f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64
"Mazda RX4" 21.0 6.0 160.0 110.0 3.9 2.62 16.46 0.0 1.0 4.0 4.0
"Mazda RX4 Wag" 21.0 6.0 160.0 110.0 3.9 2.875 17.02 0.0 1.0 4.0 4.0
"Hornet 4 Drive" 21.4 6.0 258.0 110.0 3.08 3.215 19.44 1.0 0.0 3.0 1.0
"Valiant" 18.1 6.0 225.0 105.0 2.76 3.46 20.22 1.0 0.0 3.0 1.0
"Merc 280" 19.2 6.0 167.6 123.0 3.92 3.44 18.3 1.0 0.0 4.0 4.0

9 Order

This section demonstrates how to sort a table based on one or more columns.

Code
-- Order the results by mpg in descending order and show the top 3.
SELECT model_name AS model, mpg, cyl FROM mtcars_table ORDER BY mpg DESC LIMIT 3;
3 records
model mpg cyl
Merc 240D 24.4 4
Datsun 710 22.8 4
Merc 230 22.8 4
Code
# Arrange the dataframe by mpg in descending order.
mtcars |> select(model = model_name, mpg, cyl) |> arrange(desc(mpg)) |> head(3)
                model  mpg cyl
Merc 240D   Merc 240D 24.4   4
Datsun 710 Datsun 710 22.8   4
Merc 230     Merc 230 22.8   4
Code
# Sort the dataframe by mpg in descending order.
mtcars_pd[["model_name", "mpg", "cyl"]].sort_values(by='mpg', ascending=False).head(3)
            model_name   mpg  cyl
Merc 240D    Merc 240D  24.4  4.0
Datsun 710  Datsun 710  22.8  4.0
Merc 230      Merc 230  22.8  4.0
Code
mtcars_pl.select("model_name", "mpg", "cyl").sort("mpg", descending=True).head(3)
shape: (3, 3)
model_name mpg cyl
str f64 f64
"Merc 240D" 24.4 4.0
"Datsun 710" 22.8 4.0
"Merc 230" 22.8 4.0

10 Group By

This section shows how to group rows and perform aggregate calculations.

Code
-- Group by model_name and calculate the sum of mpg and the mean of cyl.
SELECT model_name, sum(mpg) AS total_mpg, mean(cyl) AS cyl_mean FROM mtcars_table
GROUP BY 1 LIMIT 5;
5 records
model_name total_mpg cyl_mean
Merc 240D 24.4 4
Duster 360 14.3 8
Merc 230 22.8 4
Mazda RX4 21.0 6
Datsun 710 22.8 4
Code
# Group by model_name and summarize the data.
mtcars |> group_by(model_name) |> summarise(total_mpg = sum(mpg), cyl_mean = mean(cyl)) |> head(5)
# A tibble: 5 × 3
  model_name        total_mpg cyl_mean
  <chr>                 <dbl>    <dbl>
1 Datsun 710             22.8        4
2 Duster 360             14.3        8
3 Hornet 4 Drive         21.4        6
4 Hornet Sportabout      18.7        8
5 Mazda RX4              21          6
Code
# Group by model_name and aggregate the data.
mtcars_pd.groupby('model_name').agg({'mpg': 'sum', 'cyl': 'mean'}).head(5)
                    mpg  cyl
model_name                  
Datsun 710         22.8  4.0
Duster 360         14.3  8.0
Hornet 4 Drive     21.4  6.0
Hornet Sportabout  18.7  8.0
Mazda RX4          21.0  6.0
Code
mtcars_pl.group_by("model_name").agg([
    pl.sum("mpg").alias("total_mpg"),
    pl.mean("cyl").alias("cyl_mean")
]).head(5)
shape: (5, 3)
model_name total_mpg cyl_mean
str f64 f64
"Mazda RX4" 21.0 6.0
"Merc 240D" 24.4 4.0
"Datsun 710" 22.8 4.0
"Duster 360" 14.3 8.0
"Valiant" 18.1 6.0

11 Create Table

11.1 CREATE OR REPLACE

This command creates a new table or overwrites an existing one.

Code
-- Create a temporary table, replacing it if it already exists.
CREATE OR REPLACE TEMP TABLE mtcars_table_group AS
SELECT model_name, sum(mpg) AS total_mpg, mean(cyl) AS cyl_mean FROM mtcars_table
GROUP BY 1;

11.2 CREATE TABLE IF NOT EXISTS

This command creates a table only if it does not already exist.

Code
-- Create a new table only if it does not already exist.
CREATE TABLE IF NOT EXISTS new_mtcars_table_group AS
SELECT model_name, sum(mpg) AS total_mpg, mean(cyl) AS cyl_mean FROM mtcars_table
GROUP BY 1;

12 Unique

12.1 Check Unique

This section demonstrates how to verify the uniqueness of values in a column.

Code
-- Count the total number of rows and the number of distinct model names.
SELECT count(*), count(DISTINCT model_name) FROM mtcars_table;
1 records
count_star() count(DISTINCT model_name)
10 10
Code
# Count the total number of rows and the number of distinct model names.
print(len(mtcars_pd), mtcars_pd.model_name.nunique())
10 10
Code
# Count the total number of rows and the number of distinct model names.
mtcars_pl.select(pl.count(), pl.col("model_name").n_unique())
shape: (1, 2)
count model_name
u32 u32
10 10

12.2 Get Duplicate and Non-Duplicate Data

This section demonstrates how to get duplicate and non-duplicate data based on a single column.

12.2.0.1 Show all Duplicate

Code
-- Get duplicate rows based on the mpg column.
SELECT * FROM mtcars_table WHERE mpg IN (SELECT mpg FROM mtcars_table GROUP BY mpg HAVING count(*) > 1);
4 records
model_name mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2

keep non Duplicate

Code
-- Get non-duplicate rows based on the mpg column.
SELECT * FROM mtcars_table WHERE mpg IN (SELECT mpg FROM mtcars_table GROUP BY mpg HAVING count(*) = 1);
6 records
model_name mpg cyl disp hp drat wt qsec vs am gear carb
Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1
Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4
Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2
Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4

12.2.0.2 Show all Duplicate

Code
# Get duplicate rows based on the mpg column.
mtcars |> filter(duplicated(mpg) | duplicated(mpg, fromLast = TRUE))
                 model_name  mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         Mazda RX4 21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag Mazda RX4 Wag 21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710       Datsun 710 22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Merc 230           Merc 230 22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2

12.2.0.3 keep non Duplicate

Code
# Get non-duplicate rows based on the mpg column.
mtcars |> filter(!duplicated(mpg) & !duplicated(mpg, fromLast = TRUE))
                         model_name  mpg cyl  disp  hp drat    wt  qsec vs am
Hornet 4 Drive       Hornet 4 Drive 21.4   6 258.0 110 3.08 3.215 19.44  1  0
Hornet Sportabout Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0
Valiant                     Valiant 18.1   6 225.0 105 2.76 3.460 20.22  1  0
Duster 360               Duster 360 14.3   8 360.0 245 3.21 3.570 15.84  0  0
Merc 240D                 Merc 240D 24.4   4 146.7  62 3.69 3.190 20.00  1  0
Merc 280                   Merc 280 19.2   6 167.6 123 3.92 3.440 18.30  1  0
                  gear carb
Hornet 4 Drive       3    1
Hornet Sportabout    3    2
Valiant              3    1
Duster 360           3    4
Merc 240D            4    2
Merc 280             4    4

12.2.0.4 Show all Duplicate

Code
# Get duplicate rows based on the mpg column.
mtcars_pd[mtcars_pd.duplicated(subset=['mpg'], keep=False)]
                  model_name   mpg  cyl   disp  ...   am  gear  carb  new_mpg
Mazda RX4          Mazda RX4  21.0  6.0  160.0  ...  1.0   4.0   4.0     22.0
Mazda RX4 Wag  Mazda RX4 Wag  21.0  6.0  160.0  ...  1.0   4.0   4.0     22.0
Datsun 710        Datsun 710  22.8  4.0  108.0  ...  1.0   4.0   1.0     23.8
Merc 230            Merc 230  22.8  4.0  140.8  ...  0.0   4.0   2.0     23.8

[4 rows x 13 columns]

12.2.0.5 keep non Duplicate

Code
# Get non-duplicate rows based on the mpg column.
mtcars_pd[~mtcars_pd.duplicated(subset=['mpg'], keep=False)]
                          model_name   mpg  cyl  ...  gear  carb  new_mpg
Hornet 4 Drive        Hornet 4 Drive  21.4  6.0  ...   3.0   1.0     22.4
Hornet Sportabout  Hornet Sportabout  18.7  8.0  ...   3.0   2.0     19.7
Valiant                      Valiant  18.1  6.0  ...   3.0   1.0     19.1
Duster 360                Duster 360  14.3  8.0  ...   3.0   4.0     15.3
Merc 240D                  Merc 240D  24.4  4.0  ...   4.0   2.0     25.4
Merc 280                    Merc 280  19.2  6.0  ...   4.0   4.0     20.2

[6 rows x 13 columns]
Code
# Get duplicate rows based on the mpg column.
mtcars_pl.filter(pl.col("mpg").is_duplicated())
shape: (4, 12)
model_name mpg cyl disp hp drat wt qsec vs am gear carb
str f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64
"Mazda RX4" 21.0 6.0 160.0 110.0 3.9 2.62 16.46 0.0 1.0 4.0 4.0
"Mazda RX4 Wag" 21.0 6.0 160.0 110.0 3.9 2.875 17.02 0.0 1.0 4.0 4.0
"Datsun 710" 22.8 4.0 108.0 93.0 3.85 2.32 18.61 1.0 1.0 4.0 1.0
"Merc 230" 22.8 4.0 140.8 95.0 3.92 3.15 22.9 1.0 0.0 4.0 2.0

12.2.0.6 keep non Duplicate

Code
# Get non-duplicate rows based on the mpg column.
mtcars_pl.filter(pl.col("mpg").is_unique())
shape: (6, 12)
model_name mpg cyl disp hp drat wt qsec vs am gear carb
str f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64
"Hornet 4 Drive" 21.4 6.0 258.0 110.0 3.08 3.215 19.44 1.0 0.0 3.0 1.0
"Hornet Sportabout" 18.7 8.0 360.0 175.0 3.15 3.44 17.02 0.0 0.0 3.0 2.0
"Valiant" 18.1 6.0 225.0 105.0 2.76 3.46 20.22 1.0 0.0 3.0 1.0
"Duster 360" 14.3 8.0 360.0 245.0 3.21 3.57 15.84 0.0 0.0 3.0 4.0
"Merc 240D" 24.4 4.0 146.7 62.0 3.69 3.19 20.0 1.0 0.0 4.0 2.0
"Merc 280" 19.2 6.0 167.6 123.0 3.92 3.44 18.3 1.0 0.0 4.0 4.0

13 Join

Code
-- Select all data from the newly created temporary table.
SELECT * FROM mtcars_table_group t1;
Displaying records 1 - 10
model_name total_mpg cyl_mean
Mazda RX4 21.0 6
Datsun 710 22.8 4
Duster 360 14.3 8
Merc 230 22.8 4
Valiant 18.1 6
Mazda RX4 Wag 21.0 6
Hornet 4 Drive 21.4 6
Merc 280 19.2 6
Merc 240D 24.4 4
Hornet Sportabout 18.7 8

13.1 Left Join

This section shows how to perform a left join to combine data from two tables.

Code
-- Perform a left join between mtcars_table and mtcars_table_group.
SELECT t1.model_name, t1.mpg, t1.cyl, t2.* FROM mtcars_table t1
LEFT JOIN mtcars_table_group t2 ON t1.model_name = t2.model_name
LIMIT 5;
5 records
model_name mpg cyl model_name total_mpg cyl_mean
Mazda RX4 21.0 6 Mazda RX4 21.0 6
Mazda RX4 Wag 21.0 6 Mazda RX4 Wag 21.0 6
Datsun 710 22.8 4 Datsun 710 22.8 4
Hornet 4 Drive 21.4 6 Hornet 4 Drive 21.4 6
Hornet Sportabout 18.7 8 Hornet Sportabout 18.7 8
Code
# Perform a left join on the mtcars dataframe with itself.
mtcars |> left_join(mtcars, by = join_by(model_name == model_name)) |> head(5)
         model_name mpg.x cyl.x disp.x hp.x drat.x  wt.x qsec.x vs.x am.x
1         Mazda RX4  21.0     6    160  110   3.90 2.620  16.46    0    1
2     Mazda RX4 Wag  21.0     6    160  110   3.90 2.875  17.02    0    1
3        Datsun 710  22.8     4    108   93   3.85 2.320  18.61    1    1
4    Hornet 4 Drive  21.4     6    258  110   3.08 3.215  19.44    1    0
5 Hornet Sportabout  18.7     8    360  175   3.15 3.440  17.02    0    0
  gear.x carb.x mpg.y cyl.y disp.y hp.y drat.y  wt.y qsec.y vs.y am.y gear.y
1      4      4  21.0     6    160  110   3.90 2.620  16.46    0    1      4
2      4      4  21.0     6    160  110   3.90 2.875  17.02    0    1      4
3      4      1  22.8     4    108   93   3.85 2.320  18.61    1    1      4
4      3      1  21.4     6    258  110   3.08 3.215  19.44    1    0      3
5      3      2  18.7     8    360  175   3.15 3.440  17.02    0    0      3
  carb.y
1      4
2      4
3      1
4      1
5      2
Code
# Perform a left join using pandas.
pd.merge(mtcars_pd, mtcars_pd, left_on='model_name', right_on='model_name', how='left').head(5)
          model_name  mpg_x  cyl_x  disp_x  ...  am_y  gear_y  carb_y  new_mpg_y
0          Mazda RX4   21.0    6.0   160.0  ...   1.0     4.0     4.0       22.0
1      Mazda RX4 Wag   21.0    6.0   160.0  ...   1.0     4.0     4.0       22.0
2         Datsun 710   22.8    4.0   108.0  ...   1.0     4.0     1.0       23.8
3     Hornet 4 Drive   21.4    6.0   258.0  ...   0.0     3.0     1.0       22.4
4  Hornet Sportabout   18.7    8.0   360.0  ...   0.0     3.0     2.0       19.7

[5 rows x 25 columns]
Code
mtcars_pl.join(mtcars_pl, on="model_name", how="left").head(5)
shape: (5, 23)
model_name mpg cyl disp hp drat wt qsec vs am gear carb mpg_right cyl_right disp_right hp_right drat_right wt_right qsec_right vs_right am_right gear_right carb_right
str f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64
"Mazda RX4" 21.0 6.0 160.0 110.0 3.9 2.62 16.46 0.0 1.0 4.0 4.0 21.0 6.0 160.0 110.0 3.9 2.62 16.46 0.0 1.0 4.0 4.0
"Mazda RX4 Wag" 21.0 6.0 160.0 110.0 3.9 2.875 17.02 0.0 1.0 4.0 4.0 21.0 6.0 160.0 110.0 3.9 2.875 17.02 0.0 1.0 4.0 4.0
"Datsun 710" 22.8 4.0 108.0 93.0 3.85 2.32 18.61 1.0 1.0 4.0 1.0 22.8 4.0 108.0 93.0 3.85 2.32 18.61 1.0 1.0 4.0 1.0
"Hornet 4 Drive" 21.4 6.0 258.0 110.0 3.08 3.215 19.44 1.0 0.0 3.0 1.0 21.4 6.0 258.0 110.0 3.08 3.215 19.44 1.0 0.0 3.0 1.0
"Hornet Sportabout" 18.7 8.0 360.0 175.0 3.15 3.44 17.02 0.0 0.0 3.0 2.0 18.7 8.0 360.0 175.0 3.15 3.44 17.02 0.0 0.0 3.0 2.0

13.2 Inner Join

This section demonstrates how to perform an inner join.

Code
-- Perform an inner join with a subquery.
SELECT t1.model_name, t1.mpg, t1.cyl, t2.* FROM mtcars_table t1
INNER JOIN (SELECT * FROM mtcars_table_group LIMIT 5) t2 ON t1.model_name = t2.model_name;
5 records
model_name mpg cyl model_name total_mpg cyl_mean
Mazda RX4 21.0 6 Mazda RX4 21.0 6
Datsun 710 22.8 4 Datsun 710 22.8 4
Valiant 18.1 6 Valiant 18.1 6
Duster 360 14.3 8 Duster 360 14.3 8
Merc 230 22.8 4 Merc 230 22.8 4
Code
# Perform an inner join.
mtcars |> inner_join(mtcars, by = join_by(model_name == model_name)) |> head(5)
         model_name mpg.x cyl.x disp.x hp.x drat.x  wt.x qsec.x vs.x am.x
1         Mazda RX4  21.0     6    160  110   3.90 2.620  16.46    0    1
2     Mazda RX4 Wag  21.0     6    160  110   3.90 2.875  17.02    0    1
3        Datsun 710  22.8     4    108   93   3.85 2.320  18.61    1    1
4    Hornet 4 Drive  21.4     6    258  110   3.08 3.215  19.44    1    0
5 Hornet Sportabout  18.7     8    360  175   3.15 3.440  17.02    0    0
  gear.x carb.x mpg.y cyl.y disp.y hp.y drat.y  wt.y qsec.y vs.y am.y gear.y
1      4      4  21.0     6    160  110   3.90 2.620  16.46    0    1      4
2      4      4  21.0     6    160  110   3.90 2.875  17.02    0    1      4
3      4      1  22.8     4    108   93   3.85 2.320  18.61    1    1      4
4      3      1  21.4     6    258  110   3.08 3.215  19.44    1    0      3
5      3      2  18.7     8    360  175   3.15 3.440  17.02    0    0      3
  carb.y
1      4
2      4
3      1
4      1
5      2
Code
# Perform an inner join with pandas.
pd.merge(mtcars_pd, mtcars_pd, left_on='model_name', right_on='model_name', how='inner').head(5)
          model_name  mpg_x  cyl_x  disp_x  ...  am_y  gear_y  carb_y  new_mpg_y
0          Mazda RX4   21.0    6.0   160.0  ...   1.0     4.0     4.0       22.0
1      Mazda RX4 Wag   21.0    6.0   160.0  ...   1.0     4.0     4.0       22.0
2         Datsun 710   22.8    4.0   108.0  ...   1.0     4.0     1.0       23.8
3     Hornet 4 Drive   21.4    6.0   258.0  ...   0.0     3.0     1.0       22.4
4  Hornet Sportabout   18.7    8.0   360.0  ...   0.0     3.0     2.0       19.7

[5 rows x 25 columns]
Code
mtcars_pl.join(mtcars_pl, on="model_name", how="inner").head(5)
shape: (5, 23)
model_name mpg cyl disp hp drat wt qsec vs am gear carb mpg_right cyl_right disp_right hp_right drat_right wt_right qsec_right vs_right am_right gear_right carb_right
str f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64
"Mazda RX4" 21.0 6.0 160.0 110.0 3.9 2.62 16.46 0.0 1.0 4.0 4.0 21.0 6.0 160.0 110.0 3.9 2.62 16.46 0.0 1.0 4.0 4.0
"Mazda RX4 Wag" 21.0 6.0 160.0 110.0 3.9 2.875 17.02 0.0 1.0 4.0 4.0 21.0 6.0 160.0 110.0 3.9 2.875 17.02 0.0 1.0 4.0 4.0
"Datsun 710" 22.8 4.0 108.0 93.0 3.85 2.32 18.61 1.0 1.0 4.0 1.0 22.8 4.0 108.0 93.0 3.85 2.32 18.61 1.0 1.0 4.0 1.0
"Hornet 4 Drive" 21.4 6.0 258.0 110.0 3.08 3.215 19.44 1.0 0.0 3.0 1.0 21.4 6.0 258.0 110.0 3.08 3.215 19.44 1.0 0.0 3.0 1.0
"Hornet Sportabout" 18.7 8.0 360.0 175.0 3.15 3.44 17.02 0.0 0.0 3.0 2.0 18.7 8.0 360.0 175.0 3.15 3.44 17.02 0.0 0.0 3.0 2.0

14 Append Rows

14.1 Append Without Duplicate Elimination (union all)

This section shows how to combine rows from two tables, keeping all duplicates.

Code
-- Count the rows in the original table.
SELECT count(*) FROM mtcars_table;
1 records
count_star()
10
Code
-- Create a new table by appending mtcars_table to itself, including duplicates.
CREATE TEMP TABLE double_mtcars_table AS
SELECT * FROM mtcars_table
UNION ALL
SELECT * FROM mtcars_table;
Code
-- Count the rows in the new table.
SELECT count(*) FROM double_mtcars_table;
1 records
count_star()
20
Code
# Append rows using bind_rows.
mtcars %>% bind_rows(mtcars)
                              model_name  mpg cyl  disp  hp drat    wt  qsec vs
Mazda RX4...1                  Mazda RX4 21.0   6 160.0 110 3.90 2.620 16.46  0
Mazda RX4 Wag...2          Mazda RX4 Wag 21.0   6 160.0 110 3.90 2.875 17.02  0
Datsun 710...3                Datsun 710 22.8   4 108.0  93 3.85 2.320 18.61  1
Hornet 4 Drive...4        Hornet 4 Drive 21.4   6 258.0 110 3.08 3.215 19.44  1
Hornet Sportabout...5  Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0
Valiant...6                      Valiant 18.1   6 225.0 105 2.76 3.460 20.22  1
Duster 360...7                Duster 360 14.3   8 360.0 245 3.21 3.570 15.84  0
Merc 240D...8                  Merc 240D 24.4   4 146.7  62 3.69 3.190 20.00  1
Merc 230...9                    Merc 230 22.8   4 140.8  95 3.92 3.150 22.90  1
Merc 280...10                   Merc 280 19.2   6 167.6 123 3.92 3.440 18.30  1
Mazda RX4...11                 Mazda RX4 21.0   6 160.0 110 3.90 2.620 16.46  0
Mazda RX4 Wag...12         Mazda RX4 Wag 21.0   6 160.0 110 3.90 2.875 17.02  0
Datsun 710...13               Datsun 710 22.8   4 108.0  93 3.85 2.320 18.61  1
Hornet 4 Drive...14       Hornet 4 Drive 21.4   6 258.0 110 3.08 3.215 19.44  1
Hornet Sportabout...15 Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0
Valiant...16                     Valiant 18.1   6 225.0 105 2.76 3.460 20.22  1
Duster 360...17               Duster 360 14.3   8 360.0 245 3.21 3.570 15.84  0
Merc 240D...18                 Merc 240D 24.4   4 146.7  62 3.69 3.190 20.00  1
Merc 230...19                   Merc 230 22.8   4 140.8  95 3.92 3.150 22.90  1
Merc 280...20                   Merc 280 19.2   6 167.6 123 3.92 3.440 18.30  1
                       am gear carb
Mazda RX4...1           1    4    4
Mazda RX4 Wag...2       1    4    4
Datsun 710...3          1    4    1
Hornet 4 Drive...4      0    3    1
Hornet Sportabout...5   0    3    2
Valiant...6             0    3    1
Duster 360...7          0    3    4
Merc 240D...8           0    4    2
Merc 230...9            0    4    2
Merc 280...10           0    4    4
Mazda RX4...11          1    4    4
Mazda RX4 Wag...12      1    4    4
Datsun 710...13         1    4    1
Hornet 4 Drive...14     0    3    1
Hornet Sportabout...15  0    3    2
Valiant...16            0    3    1
Duster 360...17         0    3    4
Merc 240D...18          0    4    2
Merc 230...19           0    4    2
Merc 280...20           0    4    4
Code
# Concatenate dataframes, keeping all rows.
pd.concat([mtcars_pd, mtcars_pd], ignore_index=True)
           model_name   mpg  cyl   disp     hp  ...   vs   am  gear  carb  new_mpg
0           Mazda RX4  21.0  6.0  160.0  110.0  ...  0.0  1.0   4.0   4.0     22.0
1       Mazda RX4 Wag  21.0  6.0  160.0  110.0  ...  0.0  1.0   4.0   4.0     22.0
2          Datsun 710  22.8  4.0  108.0   93.0  ...  1.0  1.0   4.0   1.0     23.8
3      Hornet 4 Drive  21.4  6.0  258.0  110.0  ...  1.0  0.0   3.0   1.0     22.4
4   Hornet Sportabout  18.7  8.0  360.0  175.0  ...  0.0  0.0   3.0   2.0     19.7
5             Valiant  18.1  6.0  225.0  105.0  ...  1.0  0.0   3.0   1.0     19.1
6          Duster 360  14.3  8.0  360.0  245.0  ...  0.0  0.0   3.0   4.0     15.3
7           Merc 240D  24.4  4.0  146.7   62.0  ...  1.0  0.0   4.0   2.0     25.4
8            Merc 230  22.8  4.0  140.8   95.0  ...  1.0  0.0   4.0   2.0     23.8
9            Merc 280  19.2  6.0  167.6  123.0  ...  1.0  0.0   4.0   4.0     20.2
10          Mazda RX4  21.0  6.0  160.0  110.0  ...  0.0  1.0   4.0   4.0     22.0
11      Mazda RX4 Wag  21.0  6.0  160.0  110.0  ...  0.0  1.0   4.0   4.0     22.0
12         Datsun 710  22.8  4.0  108.0   93.0  ...  1.0  1.0   4.0   1.0     23.8
13     Hornet 4 Drive  21.4  6.0  258.0  110.0  ...  1.0  0.0   3.0   1.0     22.4
14  Hornet Sportabout  18.7  8.0  360.0  175.0  ...  0.0  0.0   3.0   2.0     19.7
15            Valiant  18.1  6.0  225.0  105.0  ...  1.0  0.0   3.0   1.0     19.1
16         Duster 360  14.3  8.0  360.0  245.0  ...  0.0  0.0   3.0   4.0     15.3
17          Merc 240D  24.4  4.0  146.7   62.0  ...  1.0  0.0   4.0   2.0     25.4
18           Merc 230  22.8  4.0  140.8   95.0  ...  1.0  0.0   4.0   2.0     23.8
19           Merc 280  19.2  6.0  167.6  123.0  ...  1.0  0.0   4.0   4.0     20.2

[20 rows x 13 columns]

14.2 Append With Duplicate Elimination (union)

This section demonstrates how to combine rows while removing duplicate entries.

Code
-- Create a table, removing duplicate rows.
CREATE OR REPLACE TEMP TABLE double_mtcars_table AS
SELECT * FROM mtcars_table
UNION
SELECT * FROM mtcars_table;
Code
-- Count the rows in the new table.
SELECT count(*) FROM double_mtcars_table;
1 records
count_star()
10
Code
-- Verify the count of distinct rows.
SELECT count(*) FROM (
  SELECT DISTINCT * FROM double_mtcars_table
);
1 records
count_star()
10
Code
# Append rows and then remove duplicates.
mtcars %>% bind_rows(mtcars) |> distinct()
                         model_name  mpg cyl  disp  hp drat    wt  qsec vs am
Mazda RX4                 Mazda RX4 21.0   6 160.0 110 3.90 2.620 16.46  0  1
Mazda RX4 Wag         Mazda RX4 Wag 21.0   6 160.0 110 3.90 2.875 17.02  0  1
Datsun 710               Datsun 710 22.8   4 108.0  93 3.85 2.320 18.61  1  1
Hornet 4 Drive       Hornet 4 Drive 21.4   6 258.0 110 3.08 3.215 19.44  1  0
Hornet Sportabout Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0
Valiant                     Valiant 18.1   6 225.0 105 2.76 3.460 20.22  1  0
Duster 360               Duster 360 14.3   8 360.0 245 3.21 3.570 15.84  0  0
Merc 240D                 Merc 240D 24.4   4 146.7  62 3.69 3.190 20.00  1  0
Merc 230                   Merc 230 22.8   4 140.8  95 3.92 3.150 22.90  1  0
Merc 280                   Merc 280 19.2   6 167.6 123 3.92 3.440 18.30  1  0
                  gear carb
Mazda RX4            4    4
Mazda RX4 Wag        4    4
Datsun 710           4    1
Hornet 4 Drive       3    1
Hornet Sportabout    3    2
Valiant              3    1
Duster 360           3    4
Merc 240D            4    2
Merc 230             4    2
Merc 280             4    4
Code
# Concatenate dataframes and then drop duplicates.
pd.concat([mtcars_pd, mtcars_pd], ignore_index=True).drop_duplicates()
          model_name   mpg  cyl   disp     hp  ...   vs   am  gear  carb  new_mpg
0          Mazda RX4  21.0  6.0  160.0  110.0  ...  0.0  1.0   4.0   4.0     22.0
1      Mazda RX4 Wag  21.0  6.0  160.0  110.0  ...  0.0  1.0   4.0   4.0     22.0
2         Datsun 710  22.8  4.0  108.0   93.0  ...  1.0  1.0   4.0   1.0     23.8
3     Hornet 4 Drive  21.4  6.0  258.0  110.0  ...  1.0  0.0   3.0   1.0     22.4
4  Hornet Sportabout  18.7  8.0  360.0  175.0  ...  0.0  0.0   3.0   2.0     19.7
5            Valiant  18.1  6.0  225.0  105.0  ...  1.0  0.0   3.0   1.0     19.1
6         Duster 360  14.3  8.0  360.0  245.0  ...  0.0  0.0   3.0   4.0     15.3
7          Merc 240D  24.4  4.0  146.7   62.0  ...  1.0  0.0   4.0   2.0     25.4
8           Merc 230  22.8  4.0  140.8   95.0  ...  1.0  0.0   4.0   2.0     23.8
9           Merc 280  19.2  6.0  167.6  123.0  ...  1.0  0.0   4.0   4.0     20.2

[10 rows x 13 columns]

15 Delete Rows

This section shows how to remove rows from a table based on a condition.

Code
-- Delete a specific row from the table.
DELETE FROM mtcars_table WHERE model_name = 'Mazda RX4';
Code
-- Verify the row count after deletion.
SELECT count(*) FROM mtcars_table;
1 records
count_star()
9
Code
# Filter out the specified row.
mtcars |> filter(model_name != 'Mazda RX4')
                         model_name  mpg cyl  disp  hp drat    wt  qsec vs am
Mazda RX4 Wag         Mazda RX4 Wag 21.0   6 160.0 110 3.90 2.875 17.02  0  1
Datsun 710               Datsun 710 22.8   4 108.0  93 3.85 2.320 18.61  1  1
Hornet 4 Drive       Hornet 4 Drive 21.4   6 258.0 110 3.08 3.215 19.44  1  0
Hornet Sportabout Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0
Valiant                     Valiant 18.1   6 225.0 105 2.76 3.460 20.22  1  0
Duster 360               Duster 360 14.3   8 360.0 245 3.21 3.570 15.84  0  0
Merc 240D                 Merc 240D 24.4   4 146.7  62 3.69 3.190 20.00  1  0
Merc 230                   Merc 230 22.8   4 140.8  95 3.92 3.150 22.90  1  0
Merc 280                   Merc 280 19.2   6 167.6 123 3.92 3.440 18.30  1  0
                  gear carb
Mazda RX4 Wag        4    4
Datsun 710           4    1
Hornet 4 Drive       3    1
Hornet Sportabout    3    2
Valiant              3    1
Duster 360           3    4
Merc 240D            4    2
Merc 230             4    2
Merc 280             4    4
Code
# Select all rows except the one specified.
mtcars_pd[mtcars_pd['model_name'] != 'Mazda RX4']
                          model_name   mpg  cyl  ...  gear  carb  new_mpg
Mazda RX4 Wag          Mazda RX4 Wag  21.0  6.0  ...   4.0   4.0     22.0
Datsun 710                Datsun 710  22.8  4.0  ...   4.0   1.0     23.8
Hornet 4 Drive        Hornet 4 Drive  21.4  6.0  ...   3.0   1.0     22.4
Hornet Sportabout  Hornet Sportabout  18.7  8.0  ...   3.0   2.0     19.7
Valiant                      Valiant  18.1  6.0  ...   3.0   1.0     19.1
Duster 360                Duster 360  14.3  8.0  ...   3.0   4.0     15.3
Merc 240D                  Merc 240D  24.4  4.0  ...   4.0   2.0     25.4
Merc 230                    Merc 230  22.8  4.0  ...   4.0   2.0     23.8
Merc 280                    Merc 280  19.2  6.0  ...   4.0   4.0     20.2

[9 rows x 13 columns]
Code
mtcars_pl.filter(pl.col("model_name") != 'Mazda RX4')
shape: (9, 12)
model_name mpg cyl disp hp drat wt qsec vs am gear carb
str f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64
"Mazda RX4 Wag" 21.0 6.0 160.0 110.0 3.9 2.875 17.02 0.0 1.0 4.0 4.0
"Datsun 710" 22.8 4.0 108.0 93.0 3.85 2.32 18.61 1.0 1.0 4.0 1.0
"Hornet 4 Drive" 21.4 6.0 258.0 110.0 3.08 3.215 19.44 1.0 0.0 3.0 1.0
"Hornet Sportabout" 18.7 8.0 360.0 175.0 3.15 3.44 17.02 0.0 0.0 3.0 2.0
"Valiant" 18.1 6.0 225.0 105.0 2.76 3.46 20.22 1.0 0.0 3.0 1.0
"Duster 360" 14.3 8.0 360.0 245.0 3.21 3.57 15.84 0.0 0.0 3.0 4.0
"Merc 240D" 24.4 4.0 146.7 62.0 3.69 3.19 20.0 1.0 0.0 4.0 2.0
"Merc 230" 22.8 4.0 140.8 95.0 3.92 3.15 22.9 1.0 0.0 4.0 2.0
"Merc 280" 19.2 6.0 167.6 123.0 3.92 3.44 18.3 1.0 0.0 4.0 4.0

16 Update Rows

This section demonstrates how to modify existing data in a table.

Code
-- Select the row to be updated.
SELECT model_name, mpg FROM mtcars_table WHERE model_name = 'Mazda RX4 Wag';
1 records
model_name mpg
Mazda RX4 Wag 21
Code
-- Update the value of a column for a specific row.
UPDATE mtcars_table
SET mpg = 999
WHERE model_name = 'Mazda RX4 Wag';
Code
-- Verify the update.
SELECT model_name, mpg FROM mtcars_table WHERE model_name = 'Mazda RX4 Wag';
1 records
model_name mpg
Mazda RX4 Wag 999
Code
# Update a value within a filtered selection.
mtcars |> filter(model_name == 'Mazda RX4 Wag') |> mutate(mpg = 999)
                 model_name mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4 Wag Mazda RX4 Wag 999   6  160 110  3.9 2.875 17.02  0  1    4    4
Code
# Update a specific value using .loc.
mtcars_pd.loc[mtcars_pd['model_name'] == 'Mazda RX4 Wag', 'mpg'] = 999
mtcars_pd
                          model_name    mpg  cyl  ...  gear  carb  new_mpg
Mazda RX4                  Mazda RX4   21.0  6.0  ...   4.0   4.0     22.0
Mazda RX4 Wag          Mazda RX4 Wag  999.0  6.0  ...   4.0   4.0     22.0
Datsun 710                Datsun 710   22.8  4.0  ...   4.0   1.0     23.8
Hornet 4 Drive        Hornet 4 Drive   21.4  6.0  ...   3.0   1.0     22.4
Hornet Sportabout  Hornet Sportabout   18.7  8.0  ...   3.0   2.0     19.7
Valiant                      Valiant   18.1  6.0  ...   3.0   1.0     19.1
Duster 360                Duster 360   14.3  8.0  ...   3.0   4.0     15.3
Merc 240D                  Merc 240D   24.4  4.0  ...   4.0   2.0     25.4
Merc 230                    Merc 230   22.8  4.0  ...   4.0   2.0     23.8
Merc 280                    Merc 280   19.2  6.0  ...   4.0   4.0     20.2

[10 rows x 13 columns]
Code
mtcars_pl.with_columns(
    pl.when(pl.col("model_name") == 'Mazda RX4 Wag')
    .then(999)
    .otherwise(pl.col("mpg"))
    .alias("mpg")
)
shape: (10, 12)
model_name mpg cyl disp hp drat wt qsec vs am gear carb
str f64 f64 f64 f64 f64 f64 f64 f64 f64 f64 f64
"Mazda RX4" 21.0 6.0 160.0 110.0 3.9 2.62 16.46 0.0 1.0 4.0 4.0
"Mazda RX4 Wag" 999.0 6.0 160.0 110.0 3.9 2.875 17.02 0.0 1.0 4.0 4.0
"Datsun 710" 22.8 4.0 108.0 93.0 3.85 2.32 18.61 1.0 1.0 4.0 1.0
"Hornet 4 Drive" 21.4 6.0 258.0 110.0 3.08 3.215 19.44 1.0 0.0 3.0 1.0
"Hornet Sportabout" 18.7 8.0 360.0 175.0 3.15 3.44 17.02 0.0 0.0 3.0 2.0
"Valiant" 18.1 6.0 225.0 105.0 2.76 3.46 20.22 1.0 0.0 3.0 1.0
"Duster 360" 14.3 8.0 360.0 245.0 3.21 3.57 15.84 0.0 0.0 3.0 4.0
"Merc 240D" 24.4 4.0 146.7 62.0 3.69 3.19 20.0 1.0 0.0 4.0 2.0
"Merc 230" 22.8 4.0 140.8 95.0 3.92 3.15 22.9 1.0 0.0 4.0 2.0
"Merc 280" 19.2 6.0 167.6 123.0 3.92 3.44 18.3 1.0 0.0 4.0 4.0

17 Drop Table

This section shows how to remove a table from the database.

Before dropping the table:

Code
-- Show all tables before dropping one.
SHOW ALL TABLES;
5 records
database schema name column_names column_types temporary
my-db main iris_table Sepal.Length, Sepal.Width , Petal.Length, Petal.Width , Species DOUBLE , DOUBLE , DOUBLE , DOUBLE , ENUM(‘setosa’, ‘versicolor’, ‘virginica’) FALSE
my-db main mtcars_table model_name, mpg , cyl , disp , hp , drat , wt , qsec , vs , am , gear , carb VARCHAR, DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE FALSE
my-db main new_mtcars_table_group model_name, total_mpg , cyl_mean VARCHAR, DOUBLE , DOUBLE FALSE
temp main double_mtcars_table model_name, mpg , cyl , disp , hp , drat , wt , qsec , vs , am , gear , carb VARCHAR, DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE TRUE
temp main mtcars_table_group model_name, total_mpg , cyl_mean VARCHAR, DOUBLE , DOUBLE TRUE

Dropping the table:

Code
-- Drop the specified table if it exists.
DROP TABLE IF EXISTS mtcars_table_group;

After dropping the table:

Code
-- Show all tables again to confirm the deletion.
SHOW ALL TABLES;
4 records
database schema name column_names column_types temporary
my-db main iris_table Sepal.Length, Sepal.Width , Petal.Length, Petal.Width , Species DOUBLE , DOUBLE , DOUBLE , DOUBLE , ENUM(‘setosa’, ‘versicolor’, ‘virginica’) FALSE
my-db main mtcars_table model_name, mpg , cyl , disp , hp , drat , wt , qsec , vs , am , gear , carb VARCHAR, DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE FALSE
my-db main new_mtcars_table_group model_name, total_mpg , cyl_mean VARCHAR, DOUBLE , DOUBLE FALSE
temp main double_mtcars_table model_name, mpg , cyl , disp , hp , drat , wt , qsec , vs , am , gear , carb VARCHAR, DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE , DOUBLE TRUE

18 PIVOT

This section demonstrates how to transform data from a long to a wide format.

Code
-- Create a temporary table for the pivot demonstration.
DROP TABLE IF EXISTS cities;
CREATE TEMP TABLE cities (
    country VARCHAR, name VARCHAR, year INTEGER, population INTEGER
);
INSERT INTO cities VALUES
    ('NL', 'Amsterdam', 2000, 1005),
    ('NL', 'Amsterdam', 2010, 1065),
    ('NL', 'Amsterdam', 2020, 1158),
    ('US', 'Seattle', 2000, 564),
    ('US', 'Seattle', 2010, 608),
    ('US', 'Seattle', 2020, 738),
    ('US', 'New York City', 2000, 8015),
    ('US', 'New York City', 2010, 8175),
    ('US', 'New York City', 2020, 8772);
Code
-- View the raw data.
SELECT * FROM cities;
9 records
country name year population
NL Amsterdam 2000 1005
NL Amsterdam 2010 1065
NL Amsterdam 2020 1158
US Seattle 2000 564
US Seattle 2010 608
US Seattle 2020 738
US New York City 2000 8015
US New York City 2010 8175
US New York City 2020 8772

18.1 PIVOT on One Column

Code
-- Pivot the table on the 'year' column.
PIVOT cities
ON year
USING sum(population)
GROUP BY country;
2 records
country 2000 2010 2020
US 8579 8783 9510
NL 1005 1065 1158
Code
cities_pd.pivot_table(index='country', columns='year', values='population', aggfunc='sum').reset_index()
year country  2000  2010  2020
0         NL  1005  1065  1158
1         US  8579  8783  9510
Code
cities_pl.pivot(index='country', columns='year', values='population', aggregate_function='sum')
shape: (2, 4)
country 2000 2010 2020
str i64 i64 i64
"NL" 1005 1065 1158
"US" 8579 8783 9510

18.2 PIVOT on Two Columns

Code
-- Pivot on both 'country' and 'name'.
PIVOT cities
ON country, name
USING sum(population);
3 records
year NL_Amsterdam NL_New York City NL_Seattle US_Amsterdam US_New York City US_Seattle
2000 1005 NA NA NA 8015 564
2010 1065 NA NA NA 8175 608
2020 1158 NA NA NA 8772 738
Code
cities_pd.pivot_table(index=['country', 'name'], columns='year', values='population', aggfunc='sum').reset_index()
year country           name  2000  2010  2020
0         NL      Amsterdam  1005  1065  1158
1         US  New York City  8015  8175  8772
2         US        Seattle   564   608   738
Code
cities_pl.pivot(index=['country', 'name'], columns='year', values='population', aggregate_function='sum')
shape: (3, 5)
country name 2000 2010 2020
str str i64 i64 i64
"NL" "Amsterdam" 1005 1065 1158
"US" "Seattle" 564 608 738
"US" "New York City" 8015 8175 8772

19 UNPIVOT

This section shows how to transform data from a wide to a long format.

Code
-- Unpivot the previously pivoted table.
UNPIVOT
(
  PIVOT cities
  ON year
  USING sum(population)
  GROUP BY country
)
ON COLUMNS(* EXCLUDE (country))
INTO
    NAME year
    VALUE population;
6 records
country year population
US 2000 8579
US 2010 8783
US 2020 9510
NL 2000 1005
NL 2010 1065
NL 2020 1158
Code
cities_pivot_pd = cities_pd.pivot_table(index='country', columns='year', values='population', aggfunc='sum').reset_index()
cities_pivot_pd.melt(id_vars='country', value_vars=[2000, 2010, 2020], var_name='year', value_name='population')
  country  year  population
0      NL  2000        1005
1      US  2000        8579
2      NL  2010        1065
3      US  2010        8783
4      NL  2020        1158
5      US  2020        9510
Code
cities_pl = pl.from_pandas(cities_pd)
Code
cities_pivot_pl = cities_pl.pivot(index='country', columns='year', values='population', aggregate_function='sum')
cities_pivot_pl.unpivot(index='country', on=['2000', '2010', '2020'], variable_name='year', value_name='population')
shape: (6, 3)
country year population
str str i64
"NL" "2000" 1005
"US" "2000" 8579
"NL" "2010" 1065
"US" "2010" 8783
"NL" "2020" 1158
"US" "2020" 9510

20 EXPLAIN

This section demonstrates how to analyze the execution plan of a query.

Code
-- Show the logical execution plan of a query.
EXPLAIN
SELECT t1.model_name, t1.mpg, t1.cyl, t2.* FROM mtcars_table t1
INNER JOIN (SELECT * FROM mtcars_table LIMIT 5) t2 ON t1.model_name = t2.model_name;
Code
-- Show the detailed execution plan, including timing information.
EXPLAIN ANALYZE
SELECT t1.model_name, t1.mpg, t1.cyl, t2.* FROM mtcars_table t1
INNER JOIN (SELECT * FROM mtcars_table LIMIT 5) t2 ON t1.model_name = t2.model_name;
Code
# Disconnect from the database and shut it down.
dbDisconnect(con, shutdown = TRUE)

21 Display Beautiful Table

This section shows how to create nicely formatted tables for presentation.

Code
# Use the gt library to create a formatted table.
library(gt)
mtcars |> gt()
model_name mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1
Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4
Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2
Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2
Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4
Code
# Use the great_tables library to create a formatted table.
from great_tables import GT
GT(mtcars_pd)
model_name mpg cyl disp hp drat wt qsec vs am gear carb new_mpg
Mazda RX4 21.0 6.0 160.0 110.0 3.9 2.62 16.46 0.0 1.0 4.0 4.0 22.0
Mazda RX4 Wag 999.0 6.0 160.0 110.0 3.9 2.875 17.02 0.0 1.0 4.0 4.0 22.0
Datsun 710 22.8 4.0 108.0 93.0 3.85 2.32 18.61 1.0 1.0 4.0 1.0 23.8
Hornet 4 Drive 21.4 6.0 258.0 110.0 3.08 3.215 19.44 1.0 0.0 3.0 1.0 22.4
Hornet Sportabout 18.7 8.0 360.0 175.0 3.15 3.44 17.02 0.0 0.0 3.0 2.0 19.7
Valiant 18.1 6.0 225.0 105.0 2.76 3.46 20.22 1.0 0.0 3.0 1.0 19.1
Duster 360 14.3 8.0 360.0 245.0 3.21 3.57 15.84 0.0 0.0 3.0 4.0 15.3
Merc 240D 24.4 4.0 146.7 62.0 3.69 3.19 20.0 1.0 0.0 4.0 2.0 25.4
Merc 230 22.8 4.0 140.8 95.0 3.92 3.15 22.9 1.0 0.0 4.0 2.0 23.8
Merc 280 19.2 6.0 167.6 123.0 3.92 3.44 18.3 1.0 0.0 4.0 4.0 20.2
Code
# Use the great_tables library to create a formatted table.
from great_tables import GT
GT(mtcars_pl)
model_name mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6.0 160.0 110.0 3.9 2.62 16.46 0.0 1.0 4.0 4.0
Mazda RX4 Wag 21.0 6.0 160.0 110.0 3.9 2.875 17.02 0.0 1.0 4.0 4.0
Datsun 710 22.8 4.0 108.0 93.0 3.85 2.32 18.61 1.0 1.0 4.0 1.0
Hornet 4 Drive 21.4 6.0 258.0 110.0 3.08 3.215 19.44 1.0 0.0 3.0 1.0
Hornet Sportabout 18.7 8.0 360.0 175.0 3.15 3.44 17.02 0.0 0.0 3.0 2.0
Valiant 18.1 6.0 225.0 105.0 2.76 3.46 20.22 1.0 0.0 3.0 1.0
Duster 360 14.3 8.0 360.0 245.0 3.21 3.57 15.84 0.0 0.0 3.0 4.0
Merc 240D 24.4 4.0 146.7 62.0 3.69 3.19 20.0 1.0 0.0 4.0 2.0
Merc 230 22.8 4.0 140.8 95.0 3.92 3.15 22.9 1.0 0.0 4.0 2.0
Merc 280 19.2 6.0 167.6 123.0 3.92 3.44 18.3 1.0 0.0 4.0 4.0

22 Reference: