Skip to content

df.apply(lambda x: x.name, axis=1) lose timezone info when df.index is tz-aware. #29052

Closed
@sliem

Description

@sliem

Copy-pastable Code Sample

import pandas as pd

df = pd.DataFrame(
    data=[0, 1, 2],
    index=[
        pd.Timestamp('2019-03-15 12:34:31.909000+0000', tz='UTC'),
        pd.Timestamp('2019-03-15 12:34:34.359000+0000', tz='UTC'),
        pd.Timestamp('2019-03-15 12:34:34.660000+0000', tz='UTC'),
    ],
)

df.apply(lambda x: x.name, axis=1)

Outputs:

2019-03-15 12:34:31.909000+00:00   2019-03-15 12:34:31.909
2019-03-15 12:34:34.359000+00:00   2019-03-15 12:34:34.359
2019-03-15 12:34:34.660000+00:00   2019-03-15 12:34:34.660
dtype: datetime64[ns]

Problem description

When applying a function on each row (axis=1) the index of that row becomes name of the serie passed to the function. Any type conversion, such as dropping timezone, is unexpected.

Workaround: df.reset_index().apply(lambda x: x["time"], axis=1)

Expected Output

Expect the timezones to be kept. E.g.

2019-03-15 12:34:31.909000+00:00   2019-03-15 12:34:31.909+00:00
2019-03-15 12:34:34.359000+00:00   2019-03-15 12:34:34.359+00:00
2019-03-15 12:34:34.660000+00:00   2019-03-15 12:34:34.660+00:00
dtype: datetime64[ns, UTC]

Output of pd.show_versions()

INSTALLED VERSIONS

commit : None
python : 3.7.4.final.0
python-bits : 64
OS : Linux
OS-release : 4.15.0-62-generic
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : en_DK.UTF-8
LOCALE : en_DK.UTF-8

pandas : 0.25.1
numpy : 1.17.2
pytz : 2019.2
dateutil : 2.8.0
pip : 19.3
setuptools : 41.2.0
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 2.10.1
IPython : 7.8.0
pandas_datareader: None
bs4 : None
bottleneck : None
fastparquet : None
gcsfs : None
lxml.etree : None
matplotlib : 3.1.1
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pytables : None
s3fs : None
scipy : 1.3.1
sqlalchemy : None
tables : None
xarray : None
xlrd : 1.2.0
xlwt : None
xlsxwriter : None

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions