Description
-
I have checked that this issue has not already been reported.
-
I have confirmed this bug exists on the latest version of pandas.
-
(optional) I have confirmed this bug exists on the master branch of pandas.
Code Sample, a copy-pastable example
bins = range(0,20,3)
labels = (
# OK:
[ [i for i in bins[:-1]]
, [(i,) for i in bins[:-1]]
, [(i,)*2 for i in bins[:-1]]
, [(i,)*3 for i in bins[:-1]]
, [pd.Timestamp(i) for i in bins[:-1]]
# Not OK:
, [(pd.Timestamp(i),) for i in bins[:-1]]
, [(pd.Timestamp(i),)*2 for i in bins[:-1]]
, [(pd.Timestamp(i),)*3 for i in bins[:-1]]
# OK:
, [(pd.Timestamp(i),i) for i in bins[:-1]]
, [(pd.Timestamp(i),i,i) for i in bins[:-1]]
, [(i,pd.Timestamp(i)) for i in bins[:-1]]
, [(i,i,pd.Timestamp(i)) for i in bins[:-1]]
, [(*(pd.Timestamp(i),)*5,i) for i in bins[:-1]]
, [(*(pd.Timestamp(i),)*5,i,i) for i in bins[:-1]]
, [(i,*(pd.Timestamp(i),)*5) for i in bins[:-1]]
, [(i,i,*(pd.Timestamp(i),)*5) for i in bins[:-1]]
, [(pd.Timestamp(i),i)*2 for i in bins[:-1]]
, [(pd.Timestamp(i),i)*3 for i in bins[:-1]]
])
for label in labels:
try:
pd.cut(range(20), bins, labels=label)
except ValueError:
print("Error:", label, "", sep="\n")
Traceback
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-2112-25ff621c28d2> in <module>
----> 1 pd.cut(range(20), bins, labels=labels[5])
.../lib/python3.8/site-packages/pandas/core/reshape/tile.py in cut(x, bins, right, labels, retbins, precision, include_lowest, duplicates, ordered)
271 raise ValueError("bins must increase monotonically.")
272
--> 273 fac, bins = _bins_to_cuts(
274 x,
275 bins,
.../lib/python3.8/site-packages/pandas/core/reshape/tile.py in _bins_to_cuts(x, bins, right, labels, precision, include_lowest, dtype, duplicates, ordered)
434 )
435 if not is_categorical_dtype(labels):
--> 436 labels = Categorical(
437 labels,
438 categories=labels if len(set(labels)) == len(labels) else None,
.../lib/python3.8/site-packages/pandas/core/arrays/categorical.py in __init__(self, values, categories, ordered, dtype, fastpath)
366
367 else:
--> 368 codes = _get_codes_for_values(values, dtype.categories)
369
370 if null_mask.any():
.../lib/python3.8/site-packages/pandas/core/arrays/categorical.py in _get_codes_for_values(values, categories)
2524 t = hash_klass(len(cats))
2525 t.map_locations(cats)
-> 2526 return coerce_indexer_dtype(t.lookup(vals), cats)
2527
2528
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.lookup()
ValueError: Buffer has wrong number of dimensions (expected 1, got 2)
Problem description
Say you are trying to cut a DataFrame:
b = pd.cut(...)
r = d.groupby(b).sum()
How do you build the resulting index? Using either the default intervals provided by the cut function or some temporary identifying labels, build the index using lookups on the input dataframe. Merging runs the risk of dropping columns even with how="left"
and validate="1:1"
. Concatenation has the same problems assuming the indices are matched. There is no simple way to lookup the value of a matching column given the value of another column (afaik) in the same row. The straightforward approach is to convert the dataframe to a dictionary for lookups and that's tedious.
Or you can just build the index from the input dataframe and pass it to the cut function via the labels
keyword. And that's why the current behaviour is a problem and why it should be fixed.
r.index = pd.MultiIndex.from_tuples(r.index, names=...)
Aside
As an aside, the documentation for the labels
parameter is lacking:
labels: array or False, default None
It can't accept numpy arrays. It can't accept MultiIndex. It can't accept DataFrame. It can't accept Series, or lists of Series. It can't accept lists of lists. That should be noted. And per my convincing argument above, the list of acceptable types should be expanded.
Output of pd.show_versions()
INSTALLED VERSIONS
commit : f2c8480
python : 3.8.8.final.0
python-bits : 64
OS : CYGWIN_NT-10.0-19041
OS-release : 3.1.7-340.x86_64
Version : 2020-08-22 17:48 UTC
machine : x86_64
processor :
byteorder : little
LC_ALL : None
LANG : None
LOCALE : en_US.UTF-8
pandas : 1.2.3
numpy : 1.20.1
pytz : 2021.1
dateutil : 2.8.1
pip : 21.0.1
setuptools : 41.2.0
Cython : 0.29.22
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 2.11.3
IPython : 7.21.0
pandas_datareader: None
bs4 : None
bottleneck : None
fsspec : None
fastparquet : None
gcsfs : None
matplotlib : 3.3.4
numexpr : 2.7.3
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyxlsb : None
s3fs : None
scipy : 1.6.1
sqlalchemy : None
tables : 3.6.1
tabulate : None
xarray : None
xlrd : None
xlwt : None
numba : None