简体   繁体   English

如何通过Pandas.DataFrame中的值筛选出值

[英]How to filter out values by values in Pandas.DataFrame

The dataFrame that I want to filter is: 我要过滤的dataFrame是:

         High    Low  Close    Volume
Date                                     
2014-06-02  634.8  622.5  628.6  13149746
2014-06-03  638.7  628.2  637.5  10419625
2014-06-04  647.9  636.1  644.8  11949821
2014-06-05  649.4  642.6  647.4  10657616
2014-06-06  651.3  644.5  645.6  12497800 
2014-06-09   93.9   91.8   93.7  74876982
2014-06-10   95.0   93.6   94.2  62458587
2015-06-11   94.8   93.5   93.9  45484122

I would like to select, for example from 2014-06-05 to the current date(2015-06-11). 我想选择从2014年6月5日到当前日期(2015年6月11日)之间的时间。 What's is the most proper way to select by comparing strings in the Date column? 比较“日期”列中的字符串,最合适的选择方式是什么?

I'd convert the 'Date' column to dtype datetime so you can do date string comparison and then you can do the following: 我将'Date'列转换为dtype datetime,因此您可以进行日期字符串比较,然后可以执行以下操作:

In [26]:

df[(df['Date'] > '2014-06-05') & (df['Date'] < '2015-06-11')]
Out[26]:
        Date   High    Low  Close    Volume
4 2014-06-06  651.3  644.5  645.6  12497800
5 2014-06-09   93.9   91.8   93.7  74876982
6 2014-06-10   95.0   93.6   94.2  62458587

So first the conversion: 因此,首先进行转换:

df['Date'] = pd.to_datetime(df['Date'])

Then the boolean condition requires using the & operator for AND and parentheses due to operator precedence. 然后,布尔条件要求对&运算符使用&运算符AND并且由于运算符优先级而需要使用括号。

EDIT 编辑

It looks like your 'Date' data is in fact the index, in which case you can still perform the datetime conversion like so: df.index = pd.to_datetime(df.index) and then filter like this: 看起来您的“日期”数据实际上是索引,在这种情况下,您仍然可以像这样执行日期时间转换: df.index = pd.to_datetime(df.index)然后进行如下过滤:

In [28]:

df[(df.index > '2014-06-05') & (df.index < '2015-06-11')]
Out[28]:
             High    Low  Close    Volume
Date                                     
2014-06-06  651.3  644.5  645.6  12497800
2014-06-09   93.9   91.8   93.7  74876982
2014-06-10   95.0   93.6   94.2  62458587

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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