BUG: dataframe sum with level drops timedelta columns · Issue #40660 · pandas-dev/pandas (original) (raw)


Code Sample, Minimal

The data:

d = pd.DataFrame( { "a": [pd.Timedelta(hours=6),pd.Timedelta(hours=7)] , "b": [12.1,13.3] })

d a b 0 0 days 06:00:00 12.1 1 0 days 07:00:00 13.3

d.dtypes a timedelta64[ns] b float64 dtype: object

The operation with unexpected results:

d.sum(level=0) b 0 12.1 1 13.3

The expected results:

d.sum(level=0) a b 0 0 days 06:00:00 12.1 1 0 days 07:00:00 13.3

Code Sample, Real-World

There's no point to summing a level without a multi-index. This example is more serious.

d = pd.DataFrame( { "a": [1,1] , "b": [2,2] , "c": [4,5] , "d": [pd.Timedelta(hours=6),pd.Timedelta(hours=7)] , "e": [12.1,13.3] })

d = d.set_index(["a","b","c"])

d d e a b c 1 2 4 0 days 06:00:00 12.1 5 0 days 07:00:00 13.3

d.dtypes d timedelta64[ns] e float64 dtype: object

Unexpected results:

d.sum(level=["a","b"]) e a b 1 2 25.4

Expected results:

d.sum(level=["a","b"]) d e a b 1 2 0 days 13:00:00 25.4

Problem description

If it can be summed without the level argument it should be summed with the level argument. At the very least, raise an error rather than dropping the column.

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