Skip to content

Instantly share code, notes, and snippets.

@do-me
Created November 22, 2023 14:29
Show Gist options
  • Select an option

  • Save do-me/a995d07efd5fdf3fbeb00e1c6e1f2452 to your computer and use it in GitHub Desktop.

Select an option

Save do-me/a995d07efd5fdf3fbeb00e1c6e1f2452 to your computer and use it in GitHub Desktop.
Pandas Jenks Natural Breaks classifier with pysal
from pysal.viz.mapclassify import NaturalBreaks as nb
import pandas as pd
# import your df here
num_classes = 5
classifier = nb(list(df["score"]), k=num_classes)
classifications = list(classifier.bins)
classifications = [0] + classifications
classifications
# [0,
# 56.80252600090453,
# 135.92383802863304,
# 245.82137512507003,
# 468.28844090592867,
# 971.1439060284617]
df['score_naturalbreak'] = pd.cut(df['score'], bins=classifications, include_lowest=True,labels=[1,2,3,4,5])
# result: new column with class numbers from 1 to 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment