我有一个pandas DataFrame,并将index设置为DateTime列:
WFM = naToZero(WFM)
我需要插入数据。但是,这个索引后来阻止我做
data['DateTime'] = pandas.to_datetime (data['DateTime'])
data = data.set_index('DateTime')
其中data = data[pandas.to_datetime (data['DateTime']) <= cutoff]
是某个日期时间。我怎么能这样做呢?
答案 0 :(得分:3)
对于比较.index
,您似乎需要DatetimeIndex
:
data['DateTime'] = pandas.to_datetime (data['DateTime'])
data = data.set_index('DateTime')
data = data[data.index <= cutoff]
同样排序DatetimeIndex
使用loc
:
data1 = data1.loc[:cutoff]
样品:
rng = pd.date_range('2017-04-03', periods=10)
data = pd.DataFrame({'a': range(10)}, index=rng)
print (data)
a
2017-04-03 0
2017-04-04 1
2017-04-05 2
2017-04-06 3
2017-04-07 4
2017-04-08 5
2017-04-09 6
2017-04-10 7
2017-04-11 8
2017-04-12 9
cutoff = '2017-04-08'
data1 = data[data.index <= cutoff]
print (data1)
a
2017-04-03 0
2017-04-04 1
2017-04-05 2
2017-04-06 3
2017-04-07 4
2017-04-08 5
data1 = data1.loc[:cutoff]
print (data1)
a
2017-04-03 0
2017-04-04 1
2017-04-05 2
2017-04-06 3
2017-04-07 4
2017-04-08 5
感谢piRSquared:
data1 = data1[:cutoff]
print (data1)
a
2017-04-03 0
2017-04-04 1
2017-04-05 2
2017-04-06 3
2017-04-07 4
2017-04-08 5