Last active
May 4, 2020 15:26
-
-
Save Ze1598/58b3af548e2429488213f698dc62e769 to your computer and use it in GitHub Desktop.
Bin data using custom intervals with pandas (integers)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import pandas as pd | |
| import numpy as np | |
| import plotly.express as px | |
| from typing import List, Union | |
| def bin_ages(age_series: pd.Series) -> pd.Series: | |
| age_labels = [f"[{i}, {i+10})" for i in range(0, 91, 10)] | |
| age_bins = pd.IntervalIndex.from_tuples( | |
| [(i, i+10) for i in range(0, 91, 10)], | |
| closed="left" | |
| ) | |
| ages_binned = pd.cut( | |
| age_series, | |
| age_bins, | |
| labels=age_labels, | |
| precision=0, | |
| include_lowest=True | |
| ) | |
| ages_binned.sort_values(ascending=True, inplace=True) | |
| # Change the values from categorical to string to be able to plot them | |
| ages_binned = ages_binned.astype("str") | |
| return ages_binned | |
| def plot_histogram( | |
| data_series: pd.Series, | |
| nbins: int, | |
| title: str, | |
| axes_titles: List[Union[str, None]] | |
| ) -> None: | |
| fig = px.histogram( | |
| x=data_series, | |
| nbins=nbins, | |
| title=title | |
| ) | |
| fig.update_layout( | |
| xaxis_title=axes_titles[0], | |
| yaxis_title=axes_titles[1] | |
| ) | |
| fig.update_layout( | |
| uniformtext_minsize=14, | |
| uniformtext_mode="hide", | |
| bargap=0, | |
| title_x=0.5 | |
| ) | |
| fig.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment