Last active
May 4, 2020 15:27
-
-
Save Ze1598/bb5bd38bd83aba3297014ea7eef4e4e1 to your computer and use it in GitHub Desktop.
Bin data using custom intervals with pandas (floats)
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_work_hours(work_hours_series: pd.Series) -> pd.Series: | |
| work_hours_labels = [f"[{i}, {i+8})" for i in range(8, 73, 8)] | |
| work_hours_bins = pd.IntervalIndex.from_tuples( | |
| [(i, i+8) for i in range(8, 73, 8)], | |
| closed="left" | |
| ) | |
| work_hours_binned = pd.cut( | |
| work_hours_series, | |
| work_hours_bins, | |
| labels=work_hours_labels, | |
| precision=2, | |
| include_lowest=True | |
| ) | |
| work_hours_binned.sort_values(ascending=True, inplace=True) | |
| # Change the values from categorical to string to be able to plot them | |
| work_hours_binned = work_hours_binned.astype("str") | |
| return work_hours_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