<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sebastiano Ferraris on Medium]]></title>
        <description><![CDATA[Stories by Sebastiano Ferraris on Medium]]></description>
        <link>https://medium.com/@sebastianof?source=rss-8c052e62452b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HvwvO-F1q3CH98Vvk4XO9w.jpeg</url>
            <title>Stories by Sebastiano Ferraris on Medium</title>
            <link>https://medium.com/@sebastianof?source=rss-8c052e62452b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 06:42:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sebastianof/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How Python: Visualise H3 hexagons in KeplerGl, and join the connected hexagons in a single polygon]]></title>
            <link>https://medium.com/@sebastianof/how-python-visualise-h3-indexes-in-keplergl-join-the-connected-geometries-3382c03a5f8a?source=rss-8c052e62452b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3382c03a5f8a</guid>
            <dc:creator><![CDATA[Sebastiano Ferraris]]></dc:creator>
            <pubDate>Thu, 12 Mar 2026 22:07:38 GMT</pubDate>
            <atom:updated>2026-03-15T11:19:21.078Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*O7McIsZuOm7Nxw517FZn0w.jpeg" /></figure><p><strong>Problem: </strong>given a set of <a href="https://h3geo.org/">H3 indexes</a>, visualise their polygons on a <a href="https://kepler.gl/">KplerGl</a> map, and then group the adjacent hexagons into their convex hulls.</p><pre># networkx==3.6.1<br># geopandas==1.0.1<br># keplergl==0.3.2<br># h3==4.4.2<br><br>from copy import deepcopy<br><br>import geopandas as gpd<br>import networkx as nx<br>import h3<br>from keplergl import KeplerGl<br>from shapely.geometry import shape<br><br><br>list_hex = [<br>    &quot;841f985ffffffff&quot;,<br>    &quot;841e355ffffffff&quot;,<br>    &quot;84194adffffffff&quot;,<br>    &quot;841f903ffffffff&quot;,<br>    &quot;841f90bffffffff&quot;,<br>    &quot;841f901ffffffff&quot;,<br>    &quot;841f905ffffffff&quot;,<br>    &quot;841f907ffffffff&quot;,<br>    &quot;841f9abffffffff&quot;,<br>    &quot;841f9b9ffffffff&quot;,<br>    &quot;841f983ffffffff&quot;,<br>    &quot;841f981ffffffff&quot;,<br>    &quot;841e309ffffffff&quot;,<br>    &quot;841e341ffffffff&quot;,<br>    &quot;841e351ffffffff&quot;,<br>    &quot;841e35dffffffff&quot;,<br>    &quot;84194a9ffffffff&quot;,<br>    &quot;84194e7ffffffff&quot;,<br>    &quot;84195d1ffffffff&quot;,<br>    &quot;84195d7ffffffff&quot;,<br>    &quot;841f987ffffffff&quot;,<br>    &quot;841e343ffffffff&quot;,<br>]<br><br>gdf_all_polygons = gpd.GeoDataFrame(<br>    {&quot;hexagons&quot;: list_hex}, <br>    geometry=[shape(h3.cells_to_geo([c])) for c in list_hex]<br>)<br><br>k_map = KeplerGl(<br>    data=deepcopy({&quot;data&quot;: gdf_all_polygons}),<br>    height=900,<br>)<br><br>k_map</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W9zwX4sugi9zCrZ-FM9paw.png" /></figure><p><strong>Note:</strong> to just visualise the hexagons, passing the h3 indexes in a column is enough. No need to convert h3 indexes to geometries.</p><p>Compute the connected components via <em>networkx</em>, then their geometries, using the handy <em>h3.cells_to_geo(list_hex)</em>, instead of more complicated convex hull computations.</p><pre>def connected_components(list_hex: list[str]) -&gt; list[list[str]]:<br>    &quot;&quot;&quot;<br>    From a list of H3 indexes returns them into clusters if <br>    they are connected components.<br>    &quot;&quot;&quot;<br>    gr = nx.Graph()<br>    gr.add_nodes_from(list_hex)<br><br>    for h3_hex in list_hex:<br>        for h3_neighbor in h3.grid_disk(h3_hex, 1):<br>            if h3_neighbor in gr:<br>                gr.add_edge(h3_hex, h3_neighbor)<br><br>    return [list(cl) for cl in sorted(list(nx.connected_components(gr)))]<br><br>hex_cc = connected_components(list_hex)<br><br>gdf_cc = gpd.GeoDataFrame(<br>    {&quot;cc_hexagons&quot;: hex_cc}, <br>    geometry=[shape(h3.cells_to_geo(cc)) for cc in hex_cc]<br>)<br><br>k_map = KeplerGl(<br>    data=deepcopy(<br>        {<br>            &quot;hexagons&quot;: gdf_all_polygons,<br>            &quot;cc&quot;: gdf_cc,<br>        }<br>    ),<br>    height=900,<br>)<br><br>k_map</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sOd4b1gCTZIX-YXi5PH8jA.gif" /></figure><p><strong>Cover image</strong></p><ul><li><a href="https://www.pierocrida.net/crida2321/insieme.htm"><strong>Piero Crida</strong>,</a> <a href="https://www.pierocrida.net/web/WATERCOL/SOURCE/59.HTM">2 Nubi</a>. Reproduced with the permission of the author.</li></ul><p><strong>References</strong></p><ul><li>GeoDsBlog reference: <a href="https://sebastianof.github.io/GeoDsBlog/posts/gds-2022-10-03-polygons-part-1/">Using polygons</a>, <a href="https://sebastianof.github.io/GeoDsBlog/posts/gds-2024-06-20-dataset-profiling/">Dataset Profiling</a></li><li>What is <a href="https://medium.com/@sebastianof/how-pyto-75a446d23273"><strong>How PyTo</strong></a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3382c03a5f8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Python: get the quarters spanning two dates and their time intervals]]></title>
            <link>https://medium.com/@sebastianof/how-python-get-the-quarters-spanning-two-dates-and-their-time-intervals-2f687f2228e3?source=rss-8c052e62452b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f687f2228e3</guid>
            <dc:creator><![CDATA[Sebastiano Ferraris]]></dc:creator>
            <pubDate>Mon, 12 Jan 2026 21:38:48 GMT</pubDate>
            <atom:updated>2026-01-12T21:40:58.029Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*AZIHXUuJZUwv--1Erxv7AQ.jpeg" /></figure><p><strong>Problem</strong>: given two dates, get the quarters spanning these dates, and the time intervals defining each quarters.</p><pre># python &gt;=3.9, pandas &gt;= 2.3.0<br>import datetime<br>import pandas as pd<br><br><br>start_date = datetime.date(2020, 1, 2)<br>end_date = datetime.date(2025, 10, 3)<br><br>num_quarters = (<br>    pd.to_datetime(end_date).to_period(freq=&quot;Q&quot;) - <br>    pd.to_datetime(start_date).to_period(freq=&quot;Q&quot;)<br>).n<br><br>period_index = pd.period_range(start_date, periods=num_quarters, freq=&quot;Q&quot;)<br><br>df_intervals = pd.DataFrame(<br>    {<br>        &quot;quarter&quot;: period_index,<br>        &quot;start_time&quot;: period_index.start_time,<br>        &quot;end_time&quot;: period_index.end_time,<br>    }<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*AQUwkLmTd8AIXQBcV7ML6Q.png" /></figure><p><strong>Images</strong></p><ul><li><em>Cover:</em> <a href="https://www.pierocrida.net/watercol/source/40.htm"><strong>Piero Crida</strong>, <em>Rezen</em>, watercolour on paper</a>. Reproduced with the permission of the author.</li></ul><p><strong>References</strong></p><ul><li>Stack overflow: <a href="https://stackoverflow.com/questions/60277350/how-to-count-the-number-of-quarters-between-two-dates">how-to-count-the-number-of-quarters-between-two-dates</a></li><li>GeoDsBlog: <a href="https://sebastianof.github.io/GeoDsBlog/posts/gds-2024-01-24-timestamp/">python datetime manipulation</a>.</li><li>What is <a href="https://medium.com/@sebastianof/how-pyto-75a446d23273"><strong>How Py</strong></a><strong>To</strong>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f687f2228e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Python: cluster sequences of timestamps into time intervals]]></title>
            <link>https://medium.com/@sebastianof/how-pyto-cluster-sequences-of-timestamps-into-time-intervals-16fed45eea8f?source=rss-8c052e62452b------2</link>
            <guid isPermaLink="false">https://medium.com/p/16fed45eea8f</guid>
            <dc:creator><![CDATA[Sebastiano Ferraris]]></dc:creator>
            <pubDate>Mon, 29 Dec 2025 05:57:01 GMT</pubDate>
            <atom:updated>2025-12-29T05:57:30.526Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h2L7Ep1L0zHGH87d6kXMFA.png" /></figure><p><strong>Problem:</strong> given a temporal series (that is a non regular time series), how to group together subsequences of timestamps that are close enough?</p><p>The solution relies on a simple one-dimensional clustering algorithm.</p><pre># python &gt;=3.9, pandas&gt;= 2.2.3<br><br>import numpy as np<br>import pandas as pd<br><br><br>def timestamp_cluster(<br>        se_timestamps: pd.Series, <br>        delta: pd.Timedelta<br>    ) -&gt; np.ndarray:<br><br>    arr_result = np.ones(len(se_timestamps), dtype=int)<br><br>    current_idx = arr_result[0]<br>    current_t = se_timestamps.iloc[0]<br><br>    for idx, ts in enumerate(se_timestamps):<br>        if ts - current_t &gt; delta:<br>            current_idx += 1<br>        current_t = ts<br>        arr_result[idx] = current_idx<br><br>    return arr_result</pre><p>To provide an example, a random series of timestamps is generated and then embedded in a pandas Datarame, with the result of `<em>timestamp_cluster</em>` in the next column.</p><pre>np.random.seed(42)<br><br><br>def random_timestamps_series(<br>        start_t: pd.Timestamp, <br>        end_t: pd.Timestamp, num: int<br>    ) -&gt; pd.Series:<br><br>    return (<br>        pd.to_datetime(<br>            np.random.randint(start_t.value, end_t.value, num) // 10**9,<br>            unit=&quot;s&quot;,<br>        )<br>        .to_series()<br>        .reset_index(drop=True)<br>    )<br><br>num = 20<br>start_t = pd.to_datetime(&quot;2025-01-01&quot;)<br>end_t = pd.to_datetime(&quot;2025-01-10&quot;)<br>delta = pd.Timedelta(days=1)<br><br># sorted random series:<br>se_ts = random_timestamps_series(<br>    start_t_min, start_t_max, num<br>).sort_values().reset_index(drop=True)<br><br># solution<br>pd.DataFrame(<br>    {<br>        &quot;time&quot;: se_ts,<br>        &quot;cluster_id&quot;: timestamp_cluster(se_ts, delta)<br>    }<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*vTA4_dMIqIfKlhLy_TwiAw.png" /></figure><p>Finally to convert the cluster id into a dataset of time intervals:</p><pre>pd.DataFrame({&quot;start_time&quot; : df.groupby(&quot;cluster_id&quot;)[&quot;time&quot;].min(), &quot;end_time&quot;: df.groupby(&quot;cluster_id&quot;)[&quot;time&quot;].max()})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*hLFFX1b6uwvpek-gujn6AQ.png" /></figure><p><strong>Images</strong></p><ul><li><em>Cover:</em> <a href="https://www.pierocrida.net/luoghi/333.HTM"><strong>Piero Crida</strong>, <em>Luoghi</em>, watercolour on paper</a>. Reproduced with the permission of the author.</li></ul><p><strong>References</strong></p><ul><li>GeoDsBlog: <a href="https://sebastianof.github.io/GeoDsBlog/posts/gds-2024-01-24-timestamp/">python datetime manipulation</a>.</li><li>What is <a href="https://medium.com/@sebastianof/how-pyto-75a446d23273"><strong>How PyTo</strong></a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16fed45eea8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Python: create a datetime timeseries and convert its type to strings and integers]]></title>
            <link>https://medium.com/@sebastianof/how-pyto-create-a-datetime-timeseries-and-convert-its-type-to-strings-and-integers-f902390f3d47?source=rss-8c052e62452b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f902390f3d47</guid>
            <dc:creator><![CDATA[Sebastiano Ferraris]]></dc:creator>
            <pubDate>Thu, 18 Dec 2025 15:52:41 GMT</pubDate>
            <atom:updated>2025-12-18T16:16:41.497Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*IH7kLrS5bWkTIM71V3zdrQ.jpeg" /></figure><p><strong>Problem:</strong> how to create a time series of datetimes, and to convert it to int using the UNIX milliseconds, and into str? Also, how to convert it back to the original format?</p><pre># python &gt;=3.9, standard libraries<br>from datetime import datetime, timedelta<br><br><br># create a list of timestamps<br>dt_start, dt_end = datetime(2022, 3, 1), datetime(2022, 3, 10)<br><br>list_ts = []<br><br>while dt_start &lt;= dt_end:<br>    list_ts.append(dt_start)<br>    dt_start += timedelta(days=1)<br><br># convert to string with specific format code<br>FORMAT_CODE = &quot;%m/%d/%Y, %H:%M:%S&quot;<br>list_str = [ts.strftime(FORMAT_CODE) for ts in list_ts]<br><br># convert from str back to datetime<br>list_ts_from_str = [datetime.strptime(st, FORMAT_CODE) for st in list_str]<br>assert list_ts_from_str == list_ts<br><br># convert to integer (milliseconds)<br>list_int = [int(st.timestamp() * 1000) for st in list_ts] <br><br># convert from milliseconds to integer<br>list_ts_from_int = [datetime.fromtimestamp(ts / 1000) for ts in list_int]<br>assert list_ts_from_int == list_ts</pre><pre>&gt;&gt;&gt; list_ts<br><br>[datetime.datetime(2022, 3, 1, 0, 0),<br> datetime.datetime(2022, 3, 2, 0, 0),<br> datetime.datetime(2022, 3, 3, 0, 0),<br> datetime.datetime(2022, 3, 4, 0, 0),<br> datetime.datetime(2022, 3, 5, 0, 0),<br> datetime.datetime(2022, 3, 6, 0, 0),<br> datetime.datetime(2022, 3, 7, 0, 0),<br> datetime.datetime(2022, 3, 8, 0, 0),<br> datetime.datetime(2022, 3, 9, 0, 0),<br> datetime.datetime(2022, 3, 10, 0, 0)]<br><br>&gt;&gt;&gt; list_str<br><br>[&#39;03/01/2022, 00:00:00&#39;,<br> &#39;03/02/2022, 00:00:00&#39;,<br> &#39;03/03/2022, 00:00:00&#39;,<br> &#39;03/04/2022, 00:00:00&#39;,<br> &#39;03/05/2022, 00:00:00&#39;,<br> &#39;03/06/2022, 00:00:00&#39;,<br> &#39;03/07/2022, 00:00:00&#39;,<br> &#39;03/08/2022, 00:00:00&#39;,<br> &#39;03/09/2022, 00:00:00&#39;,<br> &#39;03/10/2022, 00:00:00&#39;]<br><br>&gt;&gt;&gt; list_int<br><br>[1646092800000,<br> 1646179200000,<br> 1646265600000,<br> 1646352000000,<br> 1646438400000,<br> 1646524800000,<br> 1646611200000,<br> 1646697600000,<br> 1646784000000,<br> 1646870400000]</pre><p>See also the pandas library and its type pd.Timestamp , and the library pendulum.</p><p><strong>Images</strong></p><ul><li><em>Cover:</em> <a href="https://www.pierocrida.net/luoghi/333.HTM"><strong>Piero Crida</strong>, <em>Luoghi</em>, watercolour on paper</a>. Reproduced with the permission of the author.</li></ul><p><strong>References</strong></p><ul><li>GeoDsBlog: <a href="https://sebastianof.github.io/GeoDsBlog/posts/gds-2024-01-24-timestamp/">python datetime manipulation</a>.</li><li>What is <a href="https://medium.com/@sebastianof/how-pyto-75a446d23273"><strong>How PyTo</strong></a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f902390f3d47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Python: make reusable KeplerGl configuration files]]></title>
            <link>https://medium.com/@sebastianof/how-pyto-make-reusable-keplergl-configuration-files-4a774952d98b?source=rss-8c052e62452b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a774952d98b</guid>
            <dc:creator><![CDATA[Sebastiano Ferraris]]></dc:creator>
            <pubDate>Thu, 18 Dec 2025 15:52:08 GMT</pubDate>
            <atom:updated>2025-12-18T16:16:54.617Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*RUnsqKSwMecFe6GKO9ss_g.png" /></figure><p><strong>Problem:</strong> how to save and re-use <a href="https://kepler.gl/">KeplerGl</a> configuration files on multiple maps?</p><pre><br># python &gt;= 3.9, keplergl&gt;=0.3.2<br><br>from copy import deepcopy<br><br>import geopandas as gpd<br>import pandas as pd<br><br>from keplergl import KeplerGl<br><br># create some polygon in a GeoDataFrame<br><br>poly1 = {<br>    &quot;type&quot;: &quot;Polygon&quot;,<br>    &quot;coordinates&quot;: [<br>        [<br>            [-4.430164404952285, 45.43541002530209],<br>            [-7.709694216007794, 47.57951597763015],<br>            [-6.939292856754411, 40.34820196978911],<br>            [4.296639210389142, 42.36683562081022],<br>            [-3.168982247146937, 43.60089657341591],<br>            [-4.430164404952285, 45.43541002530209],<br>        ]<br>    ],<br>}<br><br>poly2 = {<br>    &quot;type&quot;: &quot;Polygon&quot;,<br>    &quot;coordinates&quot;: [<br>        [<br>            [-0.03884580472594148, 46.81947933706907],<br>            [-1.0604185658435872, 44.228521475979605],<br>            [1.5904980927525443, 39.31218569583968],<br>            [8.701191198302032, 41.52591173853426],<br>            [2.32986324065522, 45.5668859865322],<br>            [-0.03884580472594148, 46.81947933706907],<br>        ]<br>    ],<br>}<br><br>poly3 = {<br>    &quot;type&quot;: &quot;Polygon&quot;,<br>    &quot;coordinates&quot;: [<br>        [<br>            [8.839329105693219, 48.49740702124813],<br>            [3.022373222680083, 44.12857639554181],<br>            [9.078480914991756, 40.04654697919168],<br>            [15.373744378397518, 41.31235103596995],<br>            [20.038748769545673, 43.62104490090605],<br>            [9.072395596980623, 44.12028360134084],<br>            [8.839329105693219, 48.49740702124813],<br>        ]<br>    ],<br>}<br><br>gdf_regions = gpd.GeoDataFrame(<br>    pd.DataFrame(<br>        {<br>            1: [&quot;First polygon&quot;, shape(poly1)],<br>            2: [&quot;Second polygon&quot;, shape(poly2)],<br>            3: [&quot;Third polygon&quot;, shape(poly3)],<br>        },<br>        index=[&quot;name&quot;, &quot;geometry&quot;],<br>    ).T<br>)<br><br># visualise it on a map<br><br>kepler_data = deepcopy({&quot;regions&quot;: gdf_regions.__geo_interface__})<br><br>kmap = KeplerGl(<br>    data=kepler_data,<br>    height=800,<br>)<br>display(kmap)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*fdc21_6doF1z6Rn9SzW__Q.png" /></figure><p>Edit the configuration on the sidebar, e.g. change colour base on the name column:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*TyU4YDQgYGuD4wwVwdWvOw.png" /></figure><pre># Simple utils to save and load Kepler configurations<br>import json<br>from pathlib import Path, PosixPath<br><br><br>class KeplerConfigManager:<br>    &quot;&quot;&quot;Save, load and list config files for KeplerGl&quot;&quot;&quot;<br><br>    def __init__(self, path_to_folder: PosixPath = Path().cwd() / &quot;kepler_configs&quot;):<br>        self.path_to_folder = path_to_folder<br><br>    @staticmethod<br>    def _check_name(name_config: str):<br>        if name_config.endswith(&quot;.json&quot;):<br>            raise ValueError(&quot;Name of the config must not include the extension &#39;.json&#39; .&quot;)<br><br>    def _parse_name(self, name_config: str) -&gt; PosixPath:<br>        return self.path_to_folder / (name_config + &quot;.json&quot;)<br><br>    def list_available_configs(self):<br>        return [f.stem for f in self.path_to_folder.glob(&quot;*.json&quot;)]<br><br>    def save_config(self, k_map: KeplerGl, name_config: str):<br>        self._check_name(name_config)<br>        with self._parse_name(name_config).open(&quot;w+&quot;, encoding=&quot;UTF-8&quot;) as file_target:<br>            json.dump(k_map.config, file_target, indent=4)<br><br>    def load_config(self, name_config: str):<br>        self._check_name(name_config)<br>        return json.loads(self._parse_name(name_config).read_text(encoding=&quot;UTF-8&quot;))</pre><p>With the KeplerConfigManager class, save the configuration with the settings on the previous map:</p><pre>kcm = KeplerConfigManager()<br>kcm.save_config(kmap_1, &quot;configs_map_1&quot;)</pre><ul><li>Optionally edit the `configs_map_1.json` file created.</li><li>Use an instance of the same class to create a new map with the same identical configuration:</li></ul><pre>kmap_edited = KeplerGl(<br>    data=kepler_data, <br>    height=800, <br>    config=kcm.load_config(&quot;configs_map_1&quot;)<br>)<br><br>display(kmap_edited)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*yBbi8Ffzxz6lS7wp4IZpyA.png" /></figure><p><strong>Cover image</strong></p><ul><li><a href="https://www.pierocrida.net/crida2321/insieme.htm"><strong>Piero Crida</strong>, </a><a href="https://www.pierocrida.net/TEXTILES/SOURCE/12.HTM">textile</a>. Reproduced with the permission of the author.</li></ul><p><strong>References</strong></p><ul><li>GeoDsBlog reference: <a href="https://sebastianof.github.io/GeoDsBlog/posts/gds-2024-04-20-cathedrals/">Saint Michael’s Sword</a></li><li>What is <a href="https://medium.com/@sebastianof/how-pyto-75a446d23273"><strong>How PyTo</strong></a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a774952d98b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Python: Find the overlap between two time intervals]]></title>
            <link>https://medium.com/@sebastianof/how-pyto-find-the-overlap-between-two-time-intervals-93904c401120?source=rss-8c052e62452b------2</link>
            <guid isPermaLink="false">https://medium.com/p/93904c401120</guid>
            <dc:creator><![CDATA[Sebastiano Ferraris]]></dc:creator>
            <pubDate>Tue, 16 Dec 2025 19:56:09 GMT</pubDate>
            <atom:updated>2025-12-18T16:17:53.883Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*sA_IHWhfwVBy7FyLDVwpoA.jpeg" /></figure><p><strong>Problem</strong>: given 2 time intervals, how to know if they are intersecting (or overlapping)? And how to know the length of the overlap?</p><p>The overlap can be computed in one line as the maximum between the interval of length zero and the difference between the min of the intervals’ ending points minus the maximum of the intervals’ starting points.</p><pre>delta = max(0, min(t1_end, t2_end) - max(t1_start, t2_start))</pre><p>In Python, with the built indatetime library:</p><pre>from datetime import datetime, timedelta<br><br><br>def time_overlap(<br>    t1_start: datetime, <br>    t1_end: datetime, <br>    t2_start: datetime, <br>    t2_end:datetime,<br>) -&gt; timedelta:<br>    return max(<br>        timedelta(0), <br>        min(t1_end, t2_end) - max(t1_start, t2_start)<br>    )<br><br>def time_overlap_hours(<br>    t1_start: datetime, <br>    t1_end: datetime, <br>    t2_start: datetime, <br>    t2_end:datetime<br>) -&gt; float:<br>    return time_overlap(<br>        t1_start, t1_end, t2_start, t2_end<br>    ).total_seconds() / 3600    </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qs4aFLjmVvQN9itJZiaeTQ.png" /><figcaption>Time interval overlaps diagram, image by the author.</figcaption></figure><pre>&gt;&gt;&gt; time_overlap(datetime(2025,1,1,2), datetime(2025,1,1,5), datetime(2025,1,1,3), datetime(2025,1,1,9))<br><br>datetime.timedelta(seconds=7200)<br><br>&gt;&gt;&gt; time_overlap(datetime(2025,1,1,2), datetime(2025,1,1,5), datetime(2025,1,1,7), datetime(2025,1,1,9))<br><br>datetime.timedelta(0)</pre><p><strong>Cover image</strong></p><ul><li><a href="https://www.pierocrida.net/crida2321/insieme.htm"><strong>Piero Crida</strong>, <em>Insieme</em>, watercolour on paper</a>. Reproduced with the permission of the author.</li></ul><p><strong>References</strong></p><ul><li>GeoDsBlog: <a href="https://sebastianof.github.io/GeoDsBlog/posts/gds-2024-01-24-timestamp/">python datetime manipulation</a></li><li>StackOverflow: <a href="https://stackoverflow.com/questions/9044084/efficient-date-range-overlap-calculation">efficient-date-range-overlap-calculation</a></li><li>What is <a href="https://medium.com/@sebastianof/how-pyto-75a446d23273"><strong>How PyTo</strong></a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93904c401120" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Python: create random time intervals]]></title>
            <link>https://medium.com/@sebastianof/how-pyto-create-random-time-intervals-751de5891e79?source=rss-8c052e62452b------2</link>
            <guid isPermaLink="false">https://medium.com/p/751de5891e79</guid>
            <dc:creator><![CDATA[Sebastiano Ferraris]]></dc:creator>
            <pubDate>Tue, 16 Dec 2025 19:55:40 GMT</pubDate>
            <atom:updated>2025-12-18T16:18:17.315Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B87l0MQDK-a9sHDIEDdXLA.png" /></figure><p><strong>Problem:</strong> how to create a series of random time intervals?</p><pre># python &gt;=3.9, pandas &gt;= 2.3.3<br><br>import numpy as np<br>import pandas as pd<br><br># Settings and auxiliary functions<br><br>np.random.seed(0)<br><br>def random_timestamps_series(<br>    start_t: pd.Timestamp, <br>    end_t: pd.Timestamp, num: int<br>) -&gt; pd.Series:<br>    return (<br>        pd.to_datetime(<br>            np.random.randint(start_t.value, end_t.value, num) // 10**9, <br>            unit=&quot;s&quot;,<br>        )<br>        .to_series()<br>        .reset_index(drop=True)<br>    )<br><br><br># option 1: no overlaps between start interval range and end interval range<br><br>num = 10<br><br>start_t_min = pd.to_datetime(&quot;2025-01-01&quot;)<br>start_t_max = pd.to_datetime(&quot;2025-01-10&quot;)<br><br>end_t_min = pd.to_datetime(&quot;2025-01-11&quot;)<br>end_t_max = pd.to_datetime(&quot;2025-01-20&quot;)<br><br>df_intervals = pd.DataFrame(<br>    {<br>        &quot;start_timestamp&quot;: random_timestamps_series(<br>            start_t_min, start_t_max, num<br>        ),<br>        &quot;end_timestamp&quot;: random_timestamps_series(<br>              end_t_min, end_t_max, num<br>        ),<br>    }<br>)<br><br># for sanity check we add the duration column<br>df_intervals[&quot;duration&quot;] = \<br>      df_intervals[&quot;end_timestamp&quot;] - df_intervals[&quot;start_timestamp&quot;]<br><br>df_intervals</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*Az4ZIX3t_LIqaJM4CF7HMw.png" /></figure><pre># option 2: possible overlaps between start interval range and end interval range<br># it makes sure the duration is positive.<br><br>def swap_if_duration_negative(df_intervals: pd.DataFrame) -&gt; pd.DataFrame:<br>    mask_swap = df_intervals[&quot;end_timestamp&quot;] &lt; df_intervals[&quot;start_timestamp&quot;]<br><br>    df_intervals.loc[mask_swap, [&quot;start_timestamp&quot;, &quot;end_timestamp&quot;]] = df_intervals.loc[<br>        mask_swap, [&quot;end_timestamp&quot;, &quot;start_timestamp&quot;]<br>    ].values<br>    return df_intervals<br><br>num = 10<br><br>start_t_min = pd.to_datetime(&quot;2025-01-01&quot;)<br>start_t_max = pd.to_datetime(&quot;2025-01-10&quot;)<br><br>end_t_min = pd.to_datetime(&quot;2025-01-01&quot;)<br>end_t_max = pd.to_datetime(&quot;2025-01-10&quot;)<br><br>df_intervals = pd.DataFrame(<br>    {<br>        &quot;start_timestamp&quot;: random_timestamps_series(<br>            start_t_min, start_t_max, num<br>        ),<br>        &quot;end_timestamp&quot;: random_timestamps_series(<br>            end_t_min, end_t_max, num<br>        ),<br>    }<br>)<br>df_intervals = swap_if_duration_negative(df_intervals)<br><br>df_intervals[&quot;duration&quot;] = \<br>    df_intervals[&quot;end_timestamp&quot;] - df_intervals[&quot;start_timestamp&quot;]<br><br>df_intervals</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*CM8cNOw-65DG2i90Foy_3Q.png" /></figure><p><strong>Images</strong></p><ul><li>Cover: Piero Crida, <a href="https://www.mutualart.com/Artwork/SCENA-PER-USCITA-ILLUSORIA/F35062B1D85CEA95AAD4E69475EA664B"><em>Scena per uscita illusoria</em></a>, watercolour on paper. Reproduced with the permission of the author.</li></ul><p><strong>References</strong></p><ul><li><a href="https://stackoverflow.com/questions/50559078/generating-random-dates-within-a-given-range-in-pandas">StackOverflow: Generating random dates within a given range in pandas</a></li><li><a href="https://stackoverflow.com/questions/57882621/efficient-merge-overlapping-intervals-in-same-pandas-dataframe-with-start-and-fi">StackOverflow: efficient merge overlapping intervals in same pandas dataframe</a></li><li><a href="https://stackoverflow.com/questions/56421753/swap-column-values-based-on-a-condition-in-pandas">StackOverflow: swap column values based on a condition in pandas</a></li><li>GeoDsBlog: <a href="https://sebastianof.github.io/GeoDsBlog/posts/gds-2024-01-24-timestamp/">python datetime manipulation</a>.</li><li>What is <a href="https://medium.com/@sebastianof/how-pyto-75a446d23273"><strong>How PyTo</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=751de5891e79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Python: create and visualise polygons with KeplerGl]]></title>
            <link>https://medium.com/@sebastianof/how-pyto-create-and-visualise-polygons-with-keplergl-f4a5ae575862?source=rss-8c052e62452b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4a5ae575862</guid>
            <dc:creator><![CDATA[Sebastiano Ferraris]]></dc:creator>
            <pubDate>Mon, 15 Dec 2025 17:49:28 GMT</pubDate>
            <atom:updated>2025-12-18T16:18:29.975Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*ErMpEIb-b-sS1mE6JnkRjw.png" /></figure><p><strong>Problem:</strong> use <a href="https://kepler.gl/">KeplerGl</a> to manually create polygons, save them in a <a href="https://geopandas.org/en/stable/">Geopandas</a> DataFrame and plot them again on a map.</p><pre># python &gt;= 3.9, keplergl&gt;=0.3.2<br><br>from copy import deepcopy<br><br>import geopandas as gpd<br>import pandas as pd<br><br>from keplergl import KeplerGl<br>from shapely.geometry import shape<br><br><br># display an empty map and create the polygons with the drawing tools<br>kmap_1 = KeplerGl(height=800)<br>display(kmap_1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*R6Bo8rhUtm-MIlPdvaj3kQ.gif" /><figcaption>Create an empty map. Create the polygons with the drawing tool. Then copy-paste the geometry in the following cell in the jupyter notebook.</figcaption></figure><pre><br>poly1 = {<br>    &quot;type&quot;: &quot;Polygon&quot;,<br>    &quot;coordinates&quot;: [<br>        [<br>            [-4.430164404952285, 45.43541002530209],<br>            [-7.709694216007794, 47.57951597763015],<br>            [-6.939292856754411, 40.34820196978911],<br>            [4.296639210389142, 42.36683562081022],<br>            [-3.168982247146937, 43.60089657341591],<br>            [-4.430164404952285, 45.43541002530209],<br>        ]<br>    ],<br>}<br><br>poly2 = {<br>    &quot;type&quot;: &quot;Polygon&quot;,<br>    &quot;coordinates&quot;: [<br>        [<br>            [-0.03884580472594148, 46.81947933706907],<br>            [-1.0604185658435872, 44.228521475979605],<br>            [1.5904980927525443, 39.31218569583968],<br>            [8.701191198302032, 41.52591173853426],<br>            [2.32986324065522, 45.5668859865322],<br>            [-0.03884580472594148, 46.81947933706907],<br>        ]<br>    ],<br>}<br><br>poly3 = {<br>    &quot;type&quot;: &quot;Polygon&quot;,<br>    &quot;coordinates&quot;: [<br>        [<br>            [8.839329105693219, 48.49740702124813],<br>            [3.022373222680083, 44.12857639554181],<br>            [9.078480914991756, 40.04654697919168],<br>            [15.373744378397518, 41.31235103596995],<br>            [20.038748769545673, 43.62104490090605],<br>            [9.072395596980623, 44.12028360134084],<br>            [8.839329105693219, 48.49740702124813],<br>        ]<br>    ],<br>}<br><br>gdf_regions = gpd.GeoDataFrame(<br>    pd.DataFrame(<br>        {<br>            1: [&quot;First polygon&quot;, shape(poly1)],<br>            2: [&quot;Second polygon&quot;, shape(poly2)],<br>            3: [&quot;Third polygon&quot;, shape(poly3)],<br>        },<br>        index=[&quot;name&quot;, &quot;geometry&quot;],<br>    ).T<br>)<br>gdf_regions</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*a9ZcdmHiIotH86DbZkI_fw.png" /></figure><pre>kepler_data = deepcopy({&quot;regions&quot;: gdf_regions.__geo_interface__})<br><br>kmap_2 = KeplerGl(<br>    data=kepler_data,<br>    height=800,<br>)<br>display(kmap_2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*5nMKuhNbmNf0bzWwljcK7Q.png" /><figcaption>Created polygons, sourced from the GeoDataFrame, after they are passed as input to KeplerGl</figcaption></figure><p><strong>Cover image</strong></p><ul><li><a href="https://www.pierocrida.net/crida2321/insieme.htm"><strong>Piero Crida</strong>, </a><a href="https://www.pierocrida.net/textiles/source/8.htm">textile</a>. Reproduced with the permission of the author (so far without regrets).</li></ul><p><strong>References</strong></p><ul><li>GeoDsBlog reference: <a href="https://sebastianof.github.io/GeoDsBlog/posts/gds-2024-04-20-cathedrals/">Saint Michael’s Sword</a></li><li>What is <a href="https://medium.com/@sebastianof/how-pyto-75a446d23273"><strong>How PyTo</strong></a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4a5ae575862" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How PyTo]]></title>
            <link>https://medium.com/@sebastianof/how-pyto-75a446d23273?source=rss-8c052e62452b------2</link>
            <guid isPermaLink="false">https://medium.com/p/75a446d23273</guid>
            <dc:creator><![CDATA[Sebastiano Ferraris]]></dc:creator>
            <pubDate>Mon, 15 Dec 2025 17:49:16 GMT</pubDate>
            <atom:updated>2026-11-03T14:05:28.771Z</atom:updated>
            <content:encoded><![CDATA[<p>What is this snippet blog about?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O93Gai-YR_clBwvHNu29xQ.jpeg" /><figcaption><a href="https://www.fidesarte.it/it/asta-0083/piero-crida-senza-titolo-34681">Piero Crida, no title</a></figcaption></figure><p>Like many people learning Python and good coding practices while trying to find solutions to practical problems, I too, had felt the urge to share my findings and admissions of ignorance with fellow coders.<br>The platform of choice was obviously a <a href="https://sebastianof.github.io/GeoDsBlog/">blog</a> that I started in 2021, and to which I contributed — of that too, I am guilty of— with way less regularity than I had originally intended to.</p><p>Over the months I had discontinuously written a range of articles about <a href="https://sebastianof.github.io/GeoDsBlog/posts/gds.html">geospatial data science</a> and <a href="https://sebastianof.github.io/GeoDsBlog/posts/bp.html">coding practices</a>.</p><p>The blog gained traction, and a number of readers had more or less kindly told me that they had difficulties getting quickly the information they were aiming for. Despite often keeping out of each article much of the material that I had gathered, the single subset of code that could have been of help for my readers almost invariably had to be slowly dug out of an otherwise too long article.</p><p>There were two possible options to address this feedback:</p><ol><li>Continue my blog and progressively make each new article shorter and more frugal.</li><li>Create a second blog where the long articles are shredded into smaller bits, with just the problem and the code to solve it.</li></ol><p>The second solution sounded to me more appealing. Though <strong>why throw another blog out there? </strong>And why one made<strong> </strong>of snippets, when there is already StackOverflow, that is in fierce competition with an almost endless number of LLMs?</p><p>Having extensively used StackOverflow and the various LLMs, I have found that the former is of great use when you know the question, and even better when you want to post and let your answer be judged by other developers, but it is not useful to suggest the next topic you may want to have in line, in order to learn something new and relevant to your field. <br>As for the LLMs they also require you to have the question already well formulated, but the answer is often wrong, sometimes it does not even run, it does not refer to any specific Python or library version, and no other user had left a comment to try and improve it(*).</p><p>Following the readers suggestions and the above considerations, in this Medium blog, called <strong>How PyTo </strong>(how python in each articles, to make the word python appear at least once)<strong>,</strong> you will find a light and quick reference to many of the sub-topics of the main Geospatial <a href="https://sebastianof.github.io/GeoDsBlog/">blog</a> that will continue to host the more lengthy articles.</p><p>Each post here on medium will contain a basic snippet to solve a single and specific problem. If you end up here while looking for a solution to a problem you are working on, it is not unlikely that the set of posts related to the same main article may anticipate the solution to another problem you will have to work on in the near future.</p><p>Compared to the <a href="https://sebastianof.github.io/GeoDsBlog/">long version</a>, this blog has <strong>three</strong> other advantages:</p><ol><li>Medium is a well established platform, it will make the material easier to be found by a google search.</li><li>The comment section in each post will allow for feedback.</li><li>The cover images are kindly provided to us by Piero Crida. A generous and wise friend, as well as a profound artist, that you are invited to discover <a href="https://www.pierocrida.net/">here</a> and <a href="https://www.amazon.co.uk/s?k=piero+crida">there</a>.</li></ol><p>Thank you for your time, I hope you will find the navigation on this blog productive.</p><p>(*) This may have been partially true at the time of writing this article, that was December 2025. Almost a year forward, LLMs got way smarter that that, certainly making this statement obsolete. And we probably only saw the beginning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75a446d23273" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>