Skip to main content

Bins your dataframe columns into the Top ≤N categories, and "Other".

Project description

pg_binny

Discretize a whole dataframe into ≤N bins, using Top N categories.

The discretize function handles discrete & continuous columns:

  • Continuous columns are cut into N bins using supplied cutting function (defaults to qcut for quantile cuts.
  • Categorical columns: take the Top N-1, with the rest tossed into "Other"

TODO: Describe and show the plot helpers too.

Install

conda install pg_binny

-or-

pip install pg_binny

-or (locally)-

pip install -e . (That's "pip install -e dot")

How to use

Make a sample dataframe.

import pandas as pd
import pg_binny as binny


dataset = 'car_crashes'
try:
    import seaborn as sns
    df = sns.load_dataset(dataset)
except ModuleNotFoundError:
    df = pd.read_csv(f'https://raw.githubusercontent.com/mwaskom/seaborn-data/master/{dataset}.csv')
df.sample(5)
<style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; }
.dataframe tbody tr th {
    vertical-align: top;
}

.dataframe thead th {
    text-align: right;
}
</style>
total speeding alcohol not_distracted no_previous ins_premium ins_losses abbrev
19 15.1 5.738 4.530 13.137 12.684 661.88 96.57 ME
15 15.7 2.669 3.925 15.229 13.659 649.06 114.47 IA
35 14.1 3.948 4.794 13.959 11.562 697.73 133.52 OH
50 17.4 7.308 5.568 14.094 15.660 791.14 122.04 WY
43 19.4 7.760 7.372 17.654 16.878 1004.75 156.83 TX

Discretize with default bins

dfd = binny.discretize(df)
dfd.sample(5)
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-2-41b3e27056d4> in <module>
----> 1 dfd = binny.discretize(df)
      2 dfd.sample(5)
      3 


AttributeError: module 'pg_binny' has no attribute 'discretize'
dfd['speeding'].dtype
CategoricalDtype(categories=[(1.7910000000000001, 2.413], (2.413, 3.496], (3.496, 3.948], (3.948, 4.095], (4.095, 4.608], (4.608, 5.032], (5.032, 6.014], (6.014, 6.923], (6.923, 7.76], (7.76, 9.45]],
, ordered=True)
dfd['total'].dtype
CategoricalDtype(categories=[(5.899, 11.1], (11.1, 12.3], (12.3, 13.6], (13.6, 14.5], (14.5, 15.6], (15.6, 17.4], (17.4, 18.1], (18.1, 19.4], (19.4, 21.4], (21.4, 23.9]],
, ordered=True)

You can set the #bins and the cutting function (defaults to quantile cut, but you may prefer plain-old cut, or something else.

?binny.discretize
Signature:
binny.discretize(
    df,
    nbins=10,
    cut=<function qcut at 0x7fae29d843b0>,
    verbose=2,
    drop_useless=True,
)
Docstring:
Discretize columns in {df} to have at most {nbins} categories.
  * Categorical columns: take the Top n-1 plus "Other"
  * Continuous columns: cut into {nbins} using {cut}.

Returns a new discretized dataframe with the same column names.
Promotes discrete columns to categories.

Parameters
-----------
df: Dataframe to discretize
nbins: Max number of bins to use. May return fewer.
cut: Cutting method. Default `pd.qcut`. Consider pd.cut, or write your own.
verbose: 0: silent, 1: colnames, 2: (Default) top N for each column
drop_useless: Removes columns that have < 2 unique values.

Replaces numerical NA values with 'NA'.
File:      /Volumes/Peregrine/binny/pg_binny/core.py
Type:      function

Other functions

[x for x in dir(binny) if x[:2] not in ['__', 'pa', 'pd', 'rc']]
['autolabel',
 'clean_category',
 'discretize',
 'drop_singletons',
 'is_numeric',
 'isnum']
?binny.autolabel
Signature: binny.autolabel(ax, border=False) -> None
Docstring:
Label bars in a barplot {ax} with their height.
Thanks to matplotlib, composition.ai, and jsoma/chart.py.

TODO: how to label with their legend labels?
File:      /Volumes/Peregrine/binny/pg_binny/core.py
Type:      function
?binny.clean_category
Signature: binny.clean_category(df, col: str) -> None
Docstring:
Remove unused categories from df.col, inplace.
If not a category, do nothing.
File:      /Volumes/Peregrine/binny/pg_binny/core.py
Type:      function
?binny.is_numeric
Signature: binny.is_numeric(col: str)
Docstring:
Returns True iff already numeric, or can be coerced.
Usage: df.apply(is_numeric)
Usage: is_numeric(df['colname'])

Returns Boolean series.

From:
https://stackoverflow.com/questions/54426845/how-to-check-if-a-pandas-dataframe-contains-only-numeric-column-wise
File:      /Volumes/Peregrine/binny/pg_binny/core.py
Type:      function

History

pg_binny is an example extracting some frequently copy/pasted routines into a general purpose nbdev project.

Originally called binny because it bins things, that was already taken on PyPi (for... a project that bins things). The prefix pg is short for the project we were working on.

The routines and text are completely general.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pg_binny-0.0.2.tar.gz (12.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pg_binny-0.0.2-py3-none-any.whl (13.4 kB view details)

Uploaded Python 3

File details

Details for the file pg_binny-0.0.2.tar.gz.

File metadata

  • Download URL: pg_binny-0.0.2.tar.gz
  • Upload date:
  • Size: 12.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.3.0 pkginfo/1.7.0 requests/2.25.1 setuptools/52.0.0.post20210125 requests-toolbelt/0.9.1 tqdm/4.56.0 CPython/3.7.9

File hashes

Hashes for pg_binny-0.0.2.tar.gz
Algorithm Hash digest
SHA256 98842372d235afbf5d5833a96569169b26324214fad2c6de115d1cbb6a488693
MD5 d0f3b728a7859e5b086f6cb992794a8f
BLAKE2b-256 f9353fa0e37b0d63914f7ad956a194e040e48b9556bcfeea76ed416db66ea79a

See more details on using hashes here.

File details

Details for the file pg_binny-0.0.2-py3-none-any.whl.

File metadata

  • Download URL: pg_binny-0.0.2-py3-none-any.whl
  • Upload date:
  • Size: 13.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.3.0 pkginfo/1.7.0 requests/2.25.1 setuptools/52.0.0.post20210125 requests-toolbelt/0.9.1 tqdm/4.56.0 CPython/3.7.9

File hashes

Hashes for pg_binny-0.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 ec33243ae12154a2998f647b60f3cad7453a3e052b3fa5343167b017527c0e02
MD5 1eac59b2c467b618c69efbd7000a69f2
BLAKE2b-256 8f6cda3f5a2f29aa092bdccdd26b3ca249d4ac01f385e6775132608251c1e8f0

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page