简体   繁体   中英

Filter a pd.DataFrame by the type of its index elements

Is there a Pythonic way to filter a pd.DataFrame based on the type of its index elements? When reading an Excel file of time-series data, I often wish to discard rows whose indices are not datetime objects. My current solution is as follows.

import datetime
import pandas as pd

df = pd.DataFrame(index=[1, datetime.datetime(2020, 1, 1), '2019'], data=[1, 2, 3])
df[df.index.map(lambda i: isinstance(i, datetime.datetime))]

You could use a list comprehension instead of the map-lambda construction:

df[[isinstance(df.index[i], datetime.datetime) for i in range(len(df))]]

But I'm not sure that's more Pythonic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM