-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdemo6_duckdb_to_pandas.py
42 lines (36 loc) · 1.07 KB
/
demo6_duckdb_to_pandas.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import duckdb
import requests
from duckdb.typing import VARCHAR
def get(url):
return requests.get(url).text
duckdb.create_function("get", get, [VARCHAR], VARCHAR)
df = duckdb.sql("""
CREATE TABLE pokemon AS
SELECT unnest(results) AS pokemon
FROM read_json_auto('https://pokeapi.co/api/v2/pokemon?limit=10');
WITH base AS (
SELECT
pokemon.name AS name,
json(get(pokemon.url)) AS details
FROM pokemon
), pokemon_details AS (
SELECT
details.id,
name,
details.abilities::STRUCT(ability STRUCT(name VARCHAR, url VARCHAR), is_hidden BOOLEAN, slot INTEGER)[] AS abilities,
details.height,
details.weight
FROM base
)
SELECT
id,
name,
[x.ability.name FOR x IN abilities] AS abilities,
height,
weight
FROM pokemon_details;
""").df()
# Continue data wrangling in Pandas
print(df)
df_agg = df.explode("abilities").groupby("abilities").agg(count=("id", "count")).sort_values("count", ascending=False)
print(df_agg)