Python 如何禁止DatetimeIndex中除时间戳以外的键?
Pandas不将DatetimeIndex键仅限于时间戳。为什么会这样?有没有办法作出这样的限制Python 如何禁止DatetimeIndex中除时间戳以外的键?,python,pandas,datetimeindex,Python,Pandas,Datetimeindex,Pandas不将DatetimeIndex键仅限于时间戳。为什么会这样?有没有办法作出这样的限制 df = pd.DataFrame({"A":{"2019-01-01":12.0,"2019-01-03":27.0,"2019-01-04":15.0}, "B":{"2019-01-01":25.0,"2019-01-03":27.0,"2019-01-04":27.0}} ) df.index = pd.to_datet
df = pd.DataFrame({"A":{"2019-01-01":12.0,"2019-01-03":27.0,"2019-01-04":15.0},
"B":{"2019-01-01":25.0,"2019-01-03":27.0,"2019-01-04":27.0}}
)
df.index = pd.to_datetime(df.index)
df.loc['2010-05-05'] = 1 # string index
df.loc[150] = 1 # integer index
print(df)
我得到以下数据帧:
A B
2019-01-01 00:00:00 12.0 25.0
2019-01-03 00:00:00 27.0 27.0
2019-01-04 00:00:00 15.0 27.0
2010-05-05 1.0 1.0
150 1.0 1.0
我当然做不到
df.index = pd.to_datetime(df.index)
再一次因为最后两行。
然而,我想如果最后两行不能被添加抛出一个错误。
有可能吗?您可以检查每个索引是否是一个
pd.\u libs.tslibs.Timestamp.Timestamp
实例:
flags = [isinstance(idx, pd._libs.tslibs.timestamps.Timestamp) for idx in df.reset_index()['index']]
df = df[flags]
但是,请注意,您当然可以同时执行
pd.to\u datetime('2010-05-05')
和pd.to\u datetime(150)
。至少,它们仍然会产生有效的日期时间戳,而不会引发异常/错误您对索引的类型有一点误解。它不是一个DateTimeIndex
:
>>> df.index
Index([2019-01-01 00:00:00, 2019-01-03 00:00:00, 2019-01-04 00:00:00,
'2010-05-05', 150],
dtype='object')
只要添加不同的类型值,索引就会变成对象
dtype索引DateTimeIndex
的类型不能超过时间戳,索引的类型已更改
如果要从索引中删除所有非日期时间的值,可以使用pd.to\u datetime
和errors='concurve'
df.index = pd.to_datetime(df.index, errors='coerce')
要仅访问具有有效时间戳作为索引的元素,可以使用notnull
:
df[df.index.notnull()]
有趣的是,虽然pd.to_datetime(150)可以工作,但在非标量内容(如我的示例)中,它可能会抛出错误,因为混合整数和时间戳内部日期时间戳是int64,我相信这是从纪元时间算起的纳秒数。
df[df.index.notnull()]
A B
2019-01-01 12.0 25.0
2019-01-03 27.0 27.0
2019-01-04 15.0 27.0
2010-05-05 1.0 1.0