以索引列为条件的 pandas [英] Pandas conditional on index column

查看:79
本文介绍了以索引列为条件的 pandas 的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫DataFrame,并将index设置为DateTime列:

I have a pandas DataFrame, and set index to be the DateTime column:

data['DateTime'] = pandas.to_datetime (data['DateTime'])
data = data.set_index('DateTime')

我需要对数据进行插值.但是,以后该索引会阻止我这样做

which I need to interpolate the data. However, this indexing later prevents me from doing

data = data[pandas.to_datetime (data['DateTime']) <= cutoff]

,其中cutoff是某个日期时间.我该怎么办?

where cutoff is some datetime. How can I go about this?

推荐答案

似乎您需要.index进行比较DatetimeIndex:

data['DateTime'] = pandas.to_datetime (data['DateTime'])
data = data.set_index('DateTime')
data = data[data.index <= cutoff]

也已排序DatetimeIndex使用 :

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

这篇关于以索引列为条件的 pandas 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆