Python Code Hub
Colab & Jupyter-ready scripts · pandas · geopandas · scikit-learn · rasterio · matplotlibPython Code Library — Ready-to-Run Recipes
5 ready-to-run snippet(s) · curated with sample data, dataset sources & use cases
Pandas EDA — Profile any CSV
Loads any CSV and prints shape, dtypes, missing-value counts, descriptive stats, and a correlation heatmap.
First-pass exploratory data analysis for survey, health, or socio-economic data.
Beginners learning pandas; analysts profiling unfamiliar datasets.
Kaggle — World Happiness Report ↗
sample.csv · csv
country,year,gdp,life_expectancy,happiness Bangladesh,2023,2500,72.6,4.28 India,2023,2600,70.1,4.04 Nepal,2023,1300,70.8,5.39 Bhutan,2023,3500,71.8,5.17
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv('sample.csv')
print('Shape:', df.shape)
print('\nDtypes:\n', df.dtypes)
print('\nMissing:\n', df.isna().sum())
print('\nDescribe:\n', df.describe())
num = df.select_dtypes('number')
sns.heatmap(num.corr(), annot=True, cmap='RdBu_r', center=0)
plt.title('Correlation Matrix')
plt.tight_layout(); plt.show()- Shape & dtypes printout
- Missing-value counts
- Correlation heatmap
GeoPandas Choropleth Map
Join a CSV indicator to a shapefile/GeoJSON of districts and render a classified choropleth.
Visualize population density, poverty rate, NDVI averages, or disease prevalence by admin unit.
GIS analysts, public health researchers, students working with admin-level data.
indicator.csv · csv
district,literacy_rate Dhaka,76.5 Chattogram,73.2 Khulna,74.1 Rajshahi,71.8 Sylhet,68.9 Barishal,72.5Pair with a GADM Level-1 GeoJSON of Bangladesh.
import geopandas as gpd, pandas as pd, matplotlib.pyplot as plt
gdf = gpd.read_file('bangladesh_adm1.geojson')
df = pd.read_csv('indicator.csv')
merged = gdf.merge(df, left_on='NAME_1', right_on='district')
fig, ax = plt.subplots(figsize=(8, 9))
merged.plot(column='literacy_rate', cmap='YlGnBu', legend=True,
edgecolor='white', linewidth=0.6, ax=ax,
scheme='Quantiles', k=5)
ax.set_title('Literacy Rate by District'); ax.axis('off')
plt.tight_layout(); plt.show()- Classified choropleth (quantiles)
scikit-learn Random Forest Classifier
Train/test split, RF model, accuracy + confusion matrix + feature importance.
Predict outcomes from tabular survey, health, or remote-sensing features.
ML beginners with basic Python knowledge.
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, ConfusionMatrixDisplay
import pandas as pd, matplotlib.pyplot as plt
df = pd.read_csv('data.csv')
X = df.drop(columns=['target']); y = df['target']
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
clf = RandomForestClassifier(n_estimators=200, random_state=42).fit(Xtr, ytr)
print(classification_report(yte, clf.predict(Xte)))
ConfusionMatrixDisplay.from_estimator(clf, Xte, yte); plt.show()
pd.Series(clf.feature_importances_, index=X.columns).sort_values().tail(15).plot.barh()
plt.title('Feature Importance'); plt.tight_layout(); plt.show()- Classification report
- Confusion matrix
- Top-15 feature importance
Rasterio NDVI from Local TIFF
Read Red and NIR bands from a multiband GeoTIFF, compute NDVI, and save the result.
Offline NDVI workflow when you already downloaded scenes from USGS or Copernicus.
Remote sensing students working locally without GEE.
import rasterio, numpy as np
with rasterio.open('scene.tif') as src:
red = src.read(4).astype('float32')
nir = src.read(5).astype('float32')
profile = src.profile
ndvi = (nir - red) / (nir + red + 1e-9)
profile.update(count=1, dtype='float32')
with rasterio.open('ndvi.tif','w', **profile) as dst:
dst.write(ndvi, 1)
print('Saved ndvi.tif — mean:', float(np.nanmean(ndvi)))- ndvi.tif single-band raster
- Mean NDVI printout
DHS Survey Weighted Means
Compute weighted means and 95% CIs from a DHS Stata file using the survey design.
Maternal & child health indicators from Demographic & Health Surveys.
Public health researchers, epidemiologists.
import pandas as pd
from samplics.estimation import TaylorEstimator
df = pd.read_stata('BDIR81FL.DTA', convert_categoricals=False)
df['wt'] = df['v005'] / 1_000_000
est = TaylorEstimator('mean').estimate(
y=df['v201'], samp_weight=df['wt'], stratum=df['v023'], psu=df['v021']
)
print(est.to_dataframe())- Mean, SE, 95% CI table