<?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 Manoj Singh on Medium]]></title>
        <description><![CDATA[Stories by Manoj Singh on Medium]]></description>
        <link>https://medium.com/@manoj.gurdev?source=rss-7dc77cd64913------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*525y80TqL1J9rAO9</url>
            <title>Stories by Manoj Singh on Medium</title>
            <link>https://medium.com/@manoj.gurdev?source=rss-7dc77cd64913------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 11:23:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@manoj.gurdev/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[Extracting Building Footprints from Google Open Buildings with Python: A Scalable Approach for…]]></title>
            <link>https://medium.com/@manoj.gurdev/extracting-building-footprints-from-google-open-buildings-with-python-a-scalable-approach-for-2f176854d24f?source=rss-7dc77cd64913------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f176854d24f</guid>
            <category><![CDATA[parquet]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[gis]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[building-footprint]]></category>
            <dc:creator><![CDATA[Manoj Singh]]></dc:creator>
            <pubDate>Tue, 01 Apr 2025 06:43:30 GMT</pubDate>
            <atom:updated>2025-04-01T13:05:20.386Z</atom:updated>
            <content:encoded><![CDATA[<h3>Extracting Building Footprints from Google Open Buildings with Python: A Scalable Approach for Large AOIs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6dgM2x8PfLpnvd5h6RPwiA.png" /></figure><h3>Why Building Footprints Matter</h3><p>Building footprints are a foundational data layer in modern geospatial analysis. These polygon representations of building outlines are critical for applications across a wide array of sectors:</p><ul><li><strong>Urban Planning</strong>: For estimating population density, land use classification, and zoning.</li><li><strong>Infrastructure Development</strong>: Aiding road alignment, utility planning, and public facility placement.</li><li><strong>Disaster Risk Management</strong>: Assessing exposure and vulnerability in hazard-prone areas.</li><li><strong>Environmental Monitoring</strong>: Understanding urban sprawl and impervious surface dynamics.</li><li><strong>Real Estate and Market Analysis</strong>: Identifying construction trends and property distribution.</li></ul><p>However, in many regions, especially across the Global South, <strong>OpenStreetMap (OSM) data remains sparse or incomplete</strong> when it comes to building coverage. This is where <strong>Google Open Buildings</strong> — a global dataset derived from satellite imagery and machine learning — fills a critical gap.</p><h3>The Challenge: Visualizing 3GB CSV Files with Millions of Features</h3><p>While Google Open Buildings provides rich global coverage, the data is distributed in compressed CSV format, and each tile can be <strong>~3GB in size</strong> with <strong>millions of rows</strong>. Directly opening such files in QGIS can be infeasible due to memory constraints. Moreover, users are often only interested in a specific <strong>Area of Interest (AOI)</strong> rather than an entire tile.</p><p>This tutorial demonstrates a <strong>scalable Python workflow</strong> for extracting and visualizing building footprints for any custom AOI using the Google Open Buildings dataset.</p><h3>Step-by-Step Guide: Extracting Building Footprints for a Generic AOI</h3><h4>1. Install Required Libraries</h4><pre>pip install geopandas shapely pandas pyarrow</pre><h4>2. Python Script for AOI-Based Extraction</h4><pre>import pandas as pd<br>import geopandas as gpd<br>from shapely import wkt<br>from pathlib import Path<br><br># ---------------------------------------<br># Step 1: Read Google Open Buildings CSV<br># ---------------------------------------<br>csv_path = Path(&quot;/path/to/your/open_buildings_tile.csv&quot;)  # Update with actual CSV file<br>print(&quot;🔍 Loading CSV...&quot;)<br>df = pd.read_csv(csv_path)<br># Convert WKT to geometry<br>print(&quot;📐 Parsing geometries...&quot;)<br>df[&quot;geometry&quot;] = df[&quot;geometry&quot;].apply(wkt.loads)<br>gdf = gpd.GeoDataFrame(df, geometry=&quot;geometry&quot;, crs=&quot;EPSG:4326&quot;)<br># ---------------------------------------<br># Step 2: Load AOI Boundary (GeoJSON/Shapefile)<br># ---------------------------------------<br>aoi = gpd.read_file(&quot;/path/to/your/aoi_boundary.geojson&quot;)  # Replace with your AOI file path<br>aoi_geom = aoi.geometry.union_all()  # Single MultiPolygon for spatial filtering<br># ---------------------------------------<br># Step 3: Clip Buildings to AOI<br># ---------------------------------------<br>print(&quot;✂️  Clipping buildings to AOI...&quot;)<br>gdf_aoi = gdf[gdf.intersects(aoi_geom)]<br>print(f&quot;✅ Found {len(gdf_aoi):,.0f} buildings within AOI&quot;)<br># ---------------------------------------<br># Step 4: Export as GeoParquet (Efficient Format)<br># ---------------------------------------<br>output_path = Path(&quot;google_open_buildings_aoi.parquet&quot;)<br>gdf_aoi.to_parquet(output_path, index=False)<br>print(f&quot;📦 Exported clipped buildings to {output_path}&quot;)</pre><h3>Why Use GeoParquet?</h3><ul><li><strong>Efficient Storage</strong>: Much smaller file sizes compared to GeoJSON or Shapefile.</li><li><strong>Fast Read/Write</strong>: Optimized for speed, especially with large datasets.</li><li><strong>Directly Viewable in QGIS</strong>: QGIS supports .parquet as a vector layer format.</li></ul><h3>Final Thoughts</h3><p>The integration of <strong>Google Open Buildings</strong> with a <strong>Python-powered AOI extraction pipeline</strong> enables rapid, scalable, and efficient building footprint processing. For professionals working in data-scarce environments or dealing with massive geospatial datasets, this approach offers:</p><ul><li>Freedom from heavy desktop GIS tools for initial filtering.</li><li>Ability to automate and reproduce extraction workflows.</li><li>Compatibility with modern data science tools and cloud processing environments.</li></ul><p>Whether you’re a civil engineer designing water networks, a planner modeling urban growth, or a researcher analyzing urbanization trends, this method bridges a crucial data gap — turning raw CSVs into ready-to-use building layers with just a few lines of code.</p><p><strong>Resources</strong>:</p><ul><li>Google Open Buildings Project: <a href="https://sites.research.google/open-buildings/">https://sites.research.google/open-buildings/</a></li><li>GeoParquet in QGIS: <a href="https://anitagraser.com/2024/11/23/geoparquet-in-qgis-smaller-faster-files-for-the-win/">https://anitagraser.com/2024/11/23/geoparquet-in-qgis-smaller-faster-files-for-the-win/</a><a href="https://www.qgis.org/en/site/forusers/visualchangelog320/index.html#parquet-support">://www.qgis.org/en/site/forusers/visualchangelog320/index.html#parquet-support</a></li></ul><p><strong>Note</strong>: Don’t forget to explore multiple tiles if your AOI spans large areas. Merge them before filtering or run the script iteratively per tile.</p><p><em>If you found this helpful, follow for more geospatial engineering tutorials!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f176854d24f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Up a GIS and Data Science Environment with Conda: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@manoj.gurdev/setting-up-a-gis-and-data-science-environment-with-conda-a-step-by-step-guide-fc23c80acbec?source=rss-7dc77cd64913------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc23c80acbec</guid>
            <category><![CDATA[geopandas]]></category>
            <category><![CDATA[geographic]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[gis]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Manoj Singh]]></dc:creator>
            <pubDate>Wed, 05 Mar 2025 07:45:02 GMT</pubDate>
            <atom:updated>2025-03-05T10:15:45.718Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Geospatial analysis and data science are essential in solving complex real-world problems, from mapping urban infrastructure to climate modeling. If you’re a GIS and data science professional looking to set up a robust Python environment, <strong>Conda</strong> is the best tool to manage dependencies, ensuring smooth installations and compatibility.</p><p>In this guide, we’ll walk you through <strong>creating a new Conda environment</strong> tailored for GIS and data science applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4wWnEteL3n6WW7s_-JaurQ.png" /></figure><h3>Step 1: Install Anaconda or Miniconda</h3><p>Before creating a Conda environment, ensure you have <strong>Anaconda</strong> or <strong>Miniconda</strong> installed on your system.</p><ul><li><strong>Anaconda:</strong> Includes Conda, Python, and various pre-installed libraries.</li><li><strong>Miniconda:</strong> A lightweight alternative that only installs Conda and lets you add libraries as needed.</li></ul><p>📥 Download and install from:</p><ul><li><strong>Anaconda:</strong> <a href="https://www.anaconda.com/products/distribution">https://www.anaconda.com/products/distribution</a></li><li><strong>Miniconda:</strong> <a href="https://docs.conda.io/en/latest/miniconda.html">https://docs.conda.io/en/latest/miniconda.html</a></li></ul><p>Once installed, verify Conda by running:</p><pre>conda --version</pre><h3>Step 2: Create a New Conda Environment</h3><p>To keep your GIS and data science tools organized, create a dedicated environment named <strong>geo_ds</strong>:</p><pre>conda create -n geo_ds python=3.9 -y</pre><ul><li>-n geo_ds: Names the environment &quot;geo_ds.&quot;</li><li>python=3.9: Specifies Python 3.9 (adjust if needed).</li><li>-y: Skips confirmation prompts for faster installation.</li></ul><p>Activate the new environment:</p><pre>conda activate geo_ds</pre><h3>Step 3: Install Core GIS Libraries</h3><p>Now, install essential GIS libraries to handle geospatial data:</p><pre>conda install -c conda-forge geopandas shapely fiona pyproj rtree rasterio folium contextily -y</pre><ul><li><strong>Geopandas</strong>: Spatial data analysis.</li><li><strong>Shapely</strong>: Geometry handling.</li><li><strong>Fiona</strong>: File formats like shapefiles.</li><li><strong>Pyproj</strong>: Coordinate transformations.</li><li><strong>Rtree</strong>: Spatial indexing.</li><li><strong>Rasterio</strong>: Working with raster data.</li><li><strong>Folium</strong>: Interactive maps.</li><li><strong>Contextily</strong>: Basemaps for Geopandas plots.</li></ul><h3>Step 4: Install Data Science &amp; Visualization Libraries</h3><p>For data analysis and visualization, install:</p><pre>conda install -c conda-forge numpy pandas matplotlib seaborn scikit-learn scipy statsmodels tqdm -y</pre><ul><li><strong>NumPy &amp; Pandas</strong>: Data manipulation.</li><li><strong>Matplotlib &amp; Seaborn</strong>: Data visualization.</li><li><strong>Scikit-learn</strong>: Machine learning.</li><li><strong>SciPy &amp; Statsmodels</strong>: Statistical analysis.</li><li><strong>TQDM</strong>: Progress bars.</li></ul><h3>Step 5: Install Jupyter &amp; Interactive Tools</h3><p>For coding in notebooks:</p><pre>conda install -c conda-forge jupyterlab ipython ipykernel notebook -y</pre><p>Run Jupyter:</p><pre>jupyter lab</pre><h3>Step 6: Install Climate &amp; Hydrology Libraries</h3><p>For climate and water resource modeling:</p><pre>conda install -c conda-forge xarray netCDF4 h5py climate-learn metpy siphon hydropandas hydrosignatures hdsrtools imdlib -y</pre><ul><li><strong>Xarray &amp; NetCDF4</strong>: Multi-dimensional climate data.</li><li><strong>MetPy &amp; Siphon</strong>: Meteorological data analysis.</li><li><strong>Hydropandas &amp; Hydrosignatures</strong>: Hydrology modeling.</li><li><strong>IMDlib </strong>: IMD Meterelogical Datasets.</li></ul><h3>Step 7: Install Spatial &amp; Network Analysis Tools</h3><p>For spatial network analysis (e.g., urban planning, water distribution modeling):</p><pre>conda install -c conda-forge osmnx networkx -y</pre><ul><li><strong>OSMnx</strong>: OpenStreetMap data.</li><li><strong>NetworkX</strong>: Graph-based analysis.</li></ul><h3>Step 8: Install GIS Software &amp; Utilities</h3><p>For additional GIS functionalities:</p><pre>conda install -c conda-forge gdal rasterstats mapclassify richdem laspy pyproj cartopy -y</pre><ul><li><strong>GDAL</strong>: Geospatial data conversions.</li><li><strong>Rasterstats</strong>: Zonal statistics on raster data.</li><li><strong>Cartopy</strong>: Advanced mapping.</li></ul><h3>Step 9: Install Excel &amp; File Handling Libraries</h3><p>For working with reports, spreadsheets, and external data sources:</p><pre>conda install -c conda-forge openpyxl xlrd requests -y</pre><ul><li><strong>OpenPyXL &amp; xlrd</strong>: Excel file handling.</li><li><strong>Requests</strong>: API data fetching.</li></ul><h3>Step 10: Verify Your Installation</h3><p>Check if Geopandas works:</p><pre>python -c &quot;import geopandas as gpd; print(&#39;Geopandas version:&#39;, gpd.__version__)&quot;</pre><h3>Additional GIS &amp; Hydrology Tools (Optional)</h3><p>If you need more advanced geospatial tools:</p><pre># Install core Hyriver libraries<br>conda install -c conda-forge py3dep pynhd pygeoogc pygeoutils pydaymet pyprecag hydrosignatures pygeohydro -y<br><br># Hydrological modeling &amp; flood mapping tools<br>conda install -c conda-forge tauDEM pysheds swmm-toolkit -y<br><br># Install EPANET-related libraries<br>pip install wntr epanettools epanet-python -y<br><br># Install EPA-SWMM-related libraries<br>pip install pyswmm swmm-toolkit -y<br><br># Install HEC-RAS-related libraries<br>pip install raspy pyhecras h5py -y<br><br># Install HEC-HMS-related libraries<br>pip install pyHMS hydrosignature -y</pre><h3>How to Use Your GIS &amp; Data Science Environment</h3><ul><li><strong>Activate the environment before working:</strong></li></ul><pre>conda activate geo_ds</pre><ul><li><strong>Run Jupyter Notebook or Jupyter Lab:</strong></li></ul><pre>jupyter lab</pre><ul><li><strong>If you face issues, reinstall a package:</strong></li></ul><pre>conda install -c conda-forge &lt;package_name&gt;</pre><h3>Conclusion</h3><p>This guide provides a streamlined way to set up a robust Conda environment for <strong>GIS, data science, and hydrology modeling</strong>. By following these steps, you’ll have a powerful workspace ready for geospatial analysis, machine learning, and water resource engineering.</p><p>🚀 <strong>Now, start exploring geospatial data with confidence!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc23c80acbec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Time Handling in Python: A Deep Dive into datetime, pytz, relativedelta, and More]]></title>
            <link>https://medium.com/@manoj.gurdev/mastering-time-handling-in-python-a-deep-dive-into-datetime-pytz-relativedelta-and-more-05e7455aef4e?source=rss-7dc77cd64913------2</link>
            <guid isPermaLink="false">https://medium.com/p/05e7455aef4e</guid>
            <dc:creator><![CDATA[Manoj Singh]]></dc:creator>
            <pubDate>Tue, 04 Mar 2025 05:35:56 GMT</pubDate>
            <atom:updated>2025-03-04T05:35:56.730Z</atom:updated>
            <content:encoded><![CDATA[<p>Time handling is a crucial aspect of programming, whether it’s for logging events, scheduling tasks, analyzing time-series data, or handling timezone conversions. Python offers powerful libraries such as datetime, pytz, relativedelta (from dateutil), and time, among others, to simplify time manipulations.</p><p>This article explores these libraries individually with examples and then demonstrates how to combine them for advanced time computations. We will also look at their integration with pandas for real-world applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*twyC9Gfh78StPLnjNe3VSQ.png" /></figure><h3>1. Working with Python’s datetime Module</h3><p>The datetime module provides classes for manipulating dates and times. It allows creating, formatting, and performing arithmetic on datetime objects.</p><h3>Basic Usage of datetime</h3><pre>from datetime import datetime, timedelta<br><br># Current date and time<br>now = datetime.now()<br>print(&quot;Current datetime:&quot;, now)<br># Creating a specific datetime<br>dt = datetime(2023, 5, 20, 14, 30, 45)<br>print(&quot;Specific datetime:&quot;, dt)<br># Formatting datetime<br>formatted = dt.strftime(&quot;%Y-%m-%d %H:%M:%S&quot;)<br>print(&quot;Formatted datetime:&quot;, formatted)<br># Parsing datetime string<br>parsed_dt = datetime.strptime(&quot;2023-05-20 14:30:45&quot;, &quot;%Y-%m-%d %H:%M:%S&quot;)<br>print(&quot;Parsed datetime:&quot;, parsed_dt)<br># Adding time with timedelta<br>new_time = now + timedelta(days=5, hours=3)<br>print(&quot;New datetime after addition:&quot;, new_time)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*WQl0dcCO1grJaxWDZzrV5Q.png" /><figcaption>Output of datetime script</figcaption></figure><h3>Usage in Pandas</h3><pre>import pandas as pd<br><br># Creating a DataFrame with datetime column<br>df = pd.DataFrame({&#39;date&#39;: pd.date_range(start=&#39;2023-01-01&#39;, periods=5, freq=&#39;D&#39;)})<br>df[&#39;formatted_date&#39;] = df[&#39;date&#39;].dt.strftime(&#39;%Y-%m-%d %H:%M:%S&#39;)<br>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*bfRFoyWyDultk7VR1bFUEQ.png" /><figcaption>pandas output</figcaption></figure><h3>2. Handling Timezones with pytz</h3><p>Python’s datetime module does not handle time zones well by itself. The pytz library helps manage time zone conversions effectively.</p><h3>Using pytz for Timezone Handling</h3><pre>import pytz<br><br># Defining a timezone<br>tz_ny = pytz.timezone(&#39;America/New_York&#39;)<br># Localizing a naive datetime<br>dt_naive = datetime(2023, 5, 20, 14, 30)<br>dt_localized = tz_ny.localize(dt_naive)<br>print(&quot;Localized datetime:&quot;, dt_localized)<br># Converting to another timezone<br>tz_utc = pytz.utc<br>dt_utc = dt_localized.astimezone(tz_utc)<br>print(&quot;Converted to UTC:&quot;, dt_utc)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*FsK4zWk5W_bCTbNmoWo7Sw.png" /><figcaption>pytz output</figcaption></figure><h3>Usage in Pandas</h3><pre>df[&#39;date_tz&#39;] = df[&#39;date&#39;].dt.tz_localize(&#39;America/New_York&#39;)<br>df[&#39;date_utc&#39;] = df[&#39;date_tz&#39;].dt.tz_convert(&#39;UTC&#39;)<br>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*2AQpk8QcZBVq8MNLAfdMPw.png" /><figcaption>pytz output in pandas</figcaption></figure><h3>3. Advanced Date Manipulation with relativedelta</h3><p>The relativedelta class from dateutil provides more human-friendly date manipulations.</p><h3>Using relativedelta for Advanced Operations</h3><pre>from dateutil.relativedelta import relativedelta<br><br># Adding months and years<br>new_date = datetime(2023, 5, 20) + relativedelta(months=3, years=1)<br>print(&quot;New date after relativedelta:&quot;, new_date)<br># Finding the next Monday from today<br>next_monday = datetime.now() + relativedelta(weekday=0)<br>print(&quot;Next Monday:&quot;, next_monday)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*QbWqX0Rl5qZkBn6UmzkdyA.png" /><figcaption>relativedelta outputs</figcaption></figure><h3>Usage in Pandas</h3><pre>df[&#39;date_plus_3months&#39;] = df[&#39;date&#39;] + pd.DateOffset(months=3)<br>df[&#39;date_next_monday&#39;] = df[&#39;date&#39;] + pd.offsets.Week(weekday=0)<br>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*aMOzwPiYyT7Qdqo9rastVA.png" /><figcaption>relativedelta analogous in pandas</figcaption></figure><h3>4. Using time Module for Time-Related Operations</h3><p>The time module is useful for handling timestamps and measuring execution time.</p><h3>Using time Module</h3><pre>import time<br><br># Getting current timestamp<br>timestamp = time.time()<br>print(&quot;Current timestamp:&quot;, timestamp)<br># Converting timestamp to readable datetime<br>readable_dt = datetime.fromtimestamp(timestamp)<br>print(&quot;Converted from timestamp:&quot;, readable_dt)<br># Measuring execution time<br>start = time.time()<br>time.sleep(2)  # Simulating a delay<br>end = time.time()<br>print(&quot;Execution time:&quot;, end - start, &quot;seconds&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*rlMQUdUxnbfvES9xR10KMg.png" /><figcaption>time usage output</figcaption></figure><h3>Usage in Pandas</h3><pre>df[&#39;timestamp&#39;] = df[&#39;date&#39;].astype(&#39;int64&#39;) // 10**9  # Convert datetime to Unix timestamp (seconds)<br>df[&#39;from_timestamp&#39;] = pd.to_datetime(df[&#39;timestamp&#39;], unit=&#39;s&#39;)  # Convert back to datetime<br>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZmUx-Kc0vM4S6pXuSsIR9A.png" /><figcaption>timestamps conversion in pandas</figcaption></figure><h3>5. Combining datetime, pytz, relativedelta, and time</h3><p>Now, let’s see an advanced example combining these libraries.</p><h3>Example: Calculate the Last Monday of Each Month in Different Timezones</h3><pre>def last_monday_of_month(year, month, timezone_str):<br>    tz = pytz.timezone(timezone_str)<br>    last_day = datetime(year, month, 1) + relativedelta(months=1, days=-1)<br>    last_monday = last_day + relativedelta(weekday=-1)  # Last Monday<br>    return tz.localize(last_monday)<br><br># Example usage<br>last_monday_ny = last_monday_of_month(2024, 3, &#39;America/New_York&#39;)<br>last_monday_utc = last_monday_ny.astimezone(pytz.utc)<br>print(&quot;Last Monday in New York:&quot;, last_monday_ny)<br>print(&quot;Converted to UTC:&quot;, last_monday_utc)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*aquVqdhaBATiSsvFvpBB9g.png" /></figure><h3>Usage in Pandas</h3><pre>df[&#39;last_monday&#39;] = df[&#39;date&#39;].apply(lambda x: x + pd.DateOffset(day=31) - pd.offsets.Week(weekday=0))<br>df[&#39;last_monday_tz&#39;] = df[&#39;last_monday&#39;].dt.tz_localize(&#39;America/New_York&#39;).dt.tz_convert(&#39;UTC&#39;)<br>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JjEGbhc61vVhjoMlW8vDNA.png" /></figure><h3>Conclusion</h3><p>Mastering Python’s time-handling libraries can significantly improve the efficiency and accuracy of date-related operations.</p><ul><li><strong>datetime</strong> helps in creating and manipulating dates and times.</li><li><strong>pytz</strong> ensures proper timezone handling.</li><li><strong>relativedelta</strong> provides intuitive date arithmetic.</li><li><strong>time</strong> allows working with timestamps and measuring execution time.</li></ul><p>By combining these libraries, you can build powerful time-based functionalities for logging, scheduling, and data processing. Integrating them with pandas makes time-series analysis even more seamless.</p><p>Start incorporating these tools into your projects to handle date and time like a pro!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05e7455aef4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering map(), .map(),]]></title>
            <link>https://medium.com/@manoj.gurdev/mastering-map-map-24d8c7b2555d?source=rss-7dc77cd64913------2</link>
            <guid isPermaLink="false">https://medium.com/p/24d8c7b2555d</guid>
            <category><![CDATA[water-resources]]></category>
            <category><![CDATA[google-earth-engine]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Manoj Singh]]></dc:creator>
            <pubDate>Mon, 27 Jan 2025 06:11:16 GMT</pubDate>
            <atom:updated>2025-03-05T10:02:00.323Z</atom:updated>
            <content:encoded><![CDATA[<h3>Transform Data Like a Pro: Mastering map(), apply(), and Lambda Functions in Python and Earth Engine</h3><p>If you’re working in data processing or analysis, you’ve likely encountered .map(), .apply(), map(), and lambda functions in Python and JavaScript. These versatile tools allow you to efficiently apply operations to data structures, transforming raw data into actionable insights. In this article, we’ll explore their syntax, use cases, and specific examples relevant to water resources management.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ok9wYRjhaCkeAiUZFtkG3g.jpeg" /></figure><h3>1. Python’s Built-In map()</h3><p>The built-in map() function in Python applies a function to each item in an iterable (like a list or tuple) and returns a map object, which can be converted to other iterable types like lists.</p><h3>Syntax:</h3><pre>map(function, iterable)</pre><h3>Applications in Water Resources</h3><h4>Example 1: Converting Units (e.g., Inches to Millimeters)</h4><pre>def inches_to_mm(value):<br>    return value * 25.4<br><br>rainfall_inches = [2.0, 1.8, 3.2, 0.5]<br>rainfall_mm = list(map(inches_to_mm, rainfall_inches))<br>print(rainfall_mm)  # Output: [50.8, 45.72, 81.28, 12.7]</pre><h4>Example 2: Checking Flood Warning Thresholds</h4><pre>def flood_warning(flow_rate):<br>    return flow_rate &gt; 1000<br><br>flow_data = [850, 1200, 950, 1100]<br>warnings = list(map(flood_warning, flow_data))<br>print(warnings)  # Output: [False, True, False, True]</pre><h3>2. Pandas .map()</h3><p>Pandas .map() is a method for transforming Series objects by applying a function or mapping dictionary.</p><h3>Syntax:</h3><pre>Series.map(function/dict)</pre><h3>Applications in Water Resources</h3><h4>Example 1: Mapping Land Use Codes to Descriptions</h4><pre>import pandas as pd<br><br>data = pd.Series([1, 2, 3, 1, 2])<br>land_use_mapping = {1: &#39;Residential&#39;, 2: &#39;Commercial&#39;, 3: &#39;Agricultural&#39;}<br><br>mapped_land_use = data.map(land_use_mapping)<br>print(mapped_land_use)</pre><h4>Example 2: Applying Functions to Analyze Water Quality</h4><pre>def classify_ph(ph):<br>    if ph &lt; 6.5:<br>        return &quot;Acidic&quot;<br>    elif ph &gt; 8.5:<br>        return &quot;Alkaline&quot;<br>    else:<br>        return &quot;Neutral&quot;<br><br>ph_values = pd.Series([7.0, 6.2, 8.7, 7.8])<br>ph_classification = ph_values.map(classify_ph)<br>print(ph_classification)</pre><h3>3. Pandas .apply()</h3><p>The .apply() method allows you to apply a function along an axis of a DataFrame (row-wise or column-wise).</p><h3>Syntax:</h3><pre>dataframe.apply(function, axis=0/1)</pre><h3>Applications in Water Resources</h3><h4>Example 1: Calculating Water Demand Per Capita</h4><pre>def water_demand(row):<br>    return row[&#39;Total Demand (L)&#39;] / row[&#39;Population&#39;]<br><br>water_data = pd.DataFrame({<br>    &#39;Region&#39;: [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;],<br>    &#39;Total Demand (L)&#39;: [100000, 150000, 120000],<br>    &#39;Population&#39;: [5000, 7500, 6000]<br>})<br><br>water_data[&#39;Demand Per Capita&#39;] = water_data.apply(water_demand, axis=1)<br>print(water_data)</pre><h4>Example 2: Identifying Risk Levels for Reservoirs</h4><pre>def reservoir_risk(row):<br>    if row[&#39;Storage (m3)&#39;] &lt; 50000:<br>        return &#39;High Risk&#39;<br>    elif row[&#39;Storage (m3)&#39;] &lt; 100000:<br>        return &#39;Medium Risk&#39;<br>    else:<br>        return &#39;Low Risk&#39;<br><br>reservoir_data = pd.DataFrame({<br>    &#39;Reservoir&#39;: [&#39;X&#39;, &#39;Y&#39;, &#39;Z&#39;],<br>    &#39;Storage (m3)&#39;: [45000, 80000, 120000]<br>})<br><br>reservoir_data[&#39;Risk Level&#39;] = reservoir_data.apply(reservoir_risk, axis=1)<br>print(reservoir_data)</pre><h3>4. Lambda Functions in Python</h3><p>Lambda functions are anonymous, one-line functions defined using the lambda keyword. They’re often used for short, simple operations without the need to explicitly define a function using def.</p><h3>Syntax:</h3><pre>lambda arguments: expression</pre><h3>Applications in Water Resources</h3><h4>Example 1: Quick Unit Conversion</h4><pre>rainfall_inches = [2.0, 1.8, 3.2, 0.5]<br>rainfall_mm = list(map(lambda x: x * 25.4, rainfall_inches))<br>print(rainfall_mm)  # Output: [50.8, 45.72, 81.28, 12.7]</pre><h4>Example 2: Filtering Data</h4><pre>flow_data = [850, 1200, 950, 1100]<br>flood_warnings = list(filter(lambda x: x &gt; 1000, flow_data))<br>print(flood_warnings)  # Output: [1200, 1100]</pre><h4>Example 3: Sorting a DataFrame by Calculated Values</h4><pre>import pandas as pd<br><br>data = pd.DataFrame({<br>    &#39;Region&#39;: [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;],<br>    &#39;Flow (m3/s)&#39;: [120, 95, 150],<br>    &#39;Area (km2)&#39;: [50, 60, 40]<br>})<br><br>data[&#39;Flow Density&#39;] = data.apply(lambda row: row[&#39;Flow (m3/s)&#39;] / row[&#39;Area (km2)&#39;], axis=1)<br>data_sorted = data.sort_values(by=&#39;Flow Density&#39;, ascending=False)<br>print(data_sorted)</pre><h4>Example 4: Generating Labels for Plotting</h4><pre>labels = list(map(lambda x: f&#39;Region {x}&#39;, [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;]))<br>print(labels)  # Output: [&#39;Region A&#39;, &#39;Region B&#39;, &#39;Region C&#39;]</pre><h4>Example 5: Combining Columns for Analysis</h4><pre>data[&#39;Summary&#39;] = data.apply(lambda row: f&quot;{row[&#39;Region&#39;]}: {row[&#39;Flow Density&#39;]:.2f} m3/s/km2&quot;, axis=1)<br>print(data[&#39;Summary&#39;])</pre><h3>5. JavaScript .map() in Google Earth Engine (GEE)</h3><p>Google Earth Engine (GEE) leverages JavaScript’s .map() function to perform operations over collections, such as image collections or feature collections.</p><h3>Syntax:</h3><pre>collection.map(function)</pre><h3>Applications in Water Resources</h3><h4>Example 1: Calculating NDWI for Image Collection</h4><pre>var calculateNDWI = function(image) {<br>    return image.addBands(<br>        image.normalizedDifference([&#39;B3&#39;, &#39;B8&#39;]).rename(&#39;NDWI&#39;)<br>    );<br>};<br><br>var sentinelImages = ee.ImageCollection(&#39;COPERNICUS/S2&#39;)<br>    .filterBounds(region)<br>    .map(calculateNDWI);</pre><h4>Example 2: Filtering Flooded Areas</h4><pre>var classifyFlood = function(feature) {<br>    var flooded = feature.get(&#39;water_level&#39;) &gt; 1;<br>    return feature.set({&#39;Flooded&#39;: flooded});<br>};<br><br>var waterData = ee.FeatureCollection(&#39;users/water_data&#39;)<br>    .map(classifyFlood);</pre><h3>Conclusion</h3><p>By understanding the versatility of .map(), .apply(), map(), and lambda functions across Python, Pandas, and JavaScript, you can unlock powerful data transformation and analysis capabilities. These functions are particularly valuable in water resources engineering, where handling large datasets efficiently is key. Whether you&#39;re converting units, classifying risks, sorting data, or processing satellite imagery, these tools will streamline your workflow and enhance your analytical capabilities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24d8c7b2555d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extracting Half-Hourly Precipitation Time-Series Data from GPMv7 Using Google Earth Engine]]></title>
            <link>https://medium.com/@manoj.gurdev/extracting-half-hourly-precipitation-time-series-data-from-gpmv7-using-google-earth-engine-7ca642d4f272?source=rss-7dc77cd64913------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ca642d4f272</guid>
            <dc:creator><![CDATA[Manoj Singh]]></dc:creator>
            <pubDate>Thu, 23 Jan 2025 10:01:34 GMT</pubDate>
            <atom:updated>2025-01-23T16:24:17.785Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Monitoring precipitation patterns is critical for hydrological studies, flood management, and climate research. In this article, I’ll demonstrate how to extract <strong>half-hourly precipitation time-series data</strong> from the GPMv7 dataset using <strong>Google Earth Engine (GEE)</strong>. Additionally, I’ll show how to visualize the location of your point of interest and plot precipitation data for a specific time step.</p><h3>Why GPMv7?</h3><p>The <strong>Global Precipitation Measurement (GPM)</strong> mission provides high-resolution precipitation data, making it ideal for real-time applications and historical analyses. The <strong>GPM IMERG Final Run (v07)</strong> dataset offers half-hourly precipitation estimates at a spatial resolution of 0.1°.</p><h3>Step 1: Set Up Google Earth Engine</h3><p>If you’re new to GEE, sign up <a href="https://earthengine.google.com/">here</a>. Once approved:</p><ol><li>Open the <strong>Code Editor</strong>.</li><li>Familiarize yourself with the platform’s features and documentation.</li></ol><h3>Step 2: The Code</h3><p>Here’s the complete GEE code that includes geometry and dataset visualizations:</p><pre>// Define the point of interest (latitude, longitude)<br>var point = ee.Geometry.Point([latitude, longitude]);<br><br>// Load the GPM IMERG Final Run dataset<br>var gpmDataset = ee.ImageCollection(&#39;NASA/GPM_L3/IMERG_V07&#39;)<br>                  .filterDate(&#39;2023-01-01&#39;, &#39;2023-12-31&#39;) // Specify the time range<br>                  .filterBounds(point);<br><br>// Extract precipitation values for the point<br>var precipitationTimeSeries = gpmDataset.map(function(image) {<br>  var value = image.reduceRegion({<br>    reducer: ee.Reducer.first(),<br>    geometry: point,<br>    scale: 11132<br>  }).get(&#39;precipitation&#39;); // &#39;precipitation&#39; is the band name for precipitation<br>  return ee.Feature(null, {&#39;precipitation&#39;: value, &#39;date&#39;: image.date().format(&#39;YYYY-MM-dd HH:mm:ss&#39;)});<br>});<br><br>// Convert the results to a FeatureCollection<br>var timeSeries = ee.FeatureCollection(precipitationTimeSeries);<br><br>// Print the results to the Console<br>print(&#39;Precipitation Time-Series:&#39;, timeSeries.limit(48)); // Display data for 1 Day<br><br>// Visualize the point location<br>Map.centerObject(point, 7);<br>Map.addLayer(point, {color: &#39;red&#39;}, &#39;Point of Interest&#39;);<br><br>// Visualize one image from the dataset<br>var exampleImage = ee.Image(gpmDataset.first());<br>Map.addLayer(exampleImage, {bands: [&#39;precipitation&#39;], min: 0, max: 0.50, palette: [&#39;blue&#39;, &#39;green&#39;, &#39;yellow&#39;, &#39;red&#39;]}, &#39;Precipitation Example&#39;);<br><br>// Export the time-series data to Google Drive<br>Export.table.toDrive({<br>  collection: timeSeries,<br>  description: &#39;GPM_Precipitation_TimeSeries&#39;,<br>  folder: &#39;GEE_Outputs&#39;, // Specify the folder path within your Google Drive<br>  fileNamePrefix: &#39;GPM_Precip_TS_2023&#39;, // Specify filename for the export<br>  fileFormat: &#39;CSV&#39;,<br>  selectors: [&#39;date&#39;,&#39;precipitation&#39;]<br>});</pre><h3>Step 3: Visualization Details</h3><h3>1. Geometry Location Plot</h3><p>The point of interest is plotted in <strong>red</strong>, allowing you to visually confirm the location on the map. This is especially helpful for quality checks.</p><h3>2. Dataset Visualization</h3><p>The precipitation dataset is displayed for a specific time step using the following visualization parameters:</p><ul><li><strong>Bands</strong>: precipitation</li><li><strong>Min/Max Values</strong>: 0–0.50 mm/hr</li><li><strong>Palette</strong>: Blue to red gradient (blue, green, yellow, red) representing increasing precipitation intensity.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aj_4gcuYtowAUGY_EWvdJA.png" /><figcaption>Visualisation of rainfall intensity (mm/hr) at a specific time step (0.5 hourly interval)</figcaption></figure><h3>Step 4: Export and Analyze</h3><p>After running the script:</p><ol><li>Download the exported CSV file from your Google Drive.</li><li>Analyze the half-hourly data using tools like Excel, Python, or R.</li><li>Use visualizations to enhance your understanding of the spatial and temporal trends.</li></ol><h3>Applications</h3><ol><li><strong>Flood Risk Assessment</strong>: Monitor heavy rainfall events in near real-time.</li><li><strong>Water Resource Planning</strong>: Analyze seasonal precipitation patterns.</li><li><strong>Hydrological Modeling</strong>: Use high-resolution data for river flow simulations.</li></ol><h3>Example: Extracting Data for Nairobi, Kenya</h3><p>If your point of interest is <strong>Nairobi, Kenya</strong> (longitude: 36.8219, latitude: -1.2921), update the point geometry:</p><pre>var point = ee.Geometry.Point([36.8219, -1.2921]);</pre><p>Run the script to plot Nairobi’s location, visualize precipitation for one time step, and export the CSV file.</p><h3>Conclusion</h3><p>By combining time-series data extraction with visualizations, you can ensure accurate analyses and gain deeper insights into precipitation patterns. Google Earth Engine provides a robust platform for handling large datasets, making it easier to integrate geospatial and temporal analyses.</p><p>Feel free to adapt this script to your needs, and share your visualizations or challenges in the comments below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ca642d4f272" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>