[英]Select rows from pandas dataframe with dates
Given a simple data frame 给定一个简单的数据框
df = pd.DataFrame(np.random.rand(5,3))
I can select the records with the labels 1 and 3 using 我可以使用来选择带有标签1和3的记录
df.loc[[1,3]]
But, if I change alter the index so it uses dates... 但是,如果我更改索引,则它使用日期...
df.index = pd.date_range('1/1/2010', periods=5)
this no longer works: 这不再起作用:
df.loc[['2010-01-02', '2010-01-04']]
KeyError: "None of [['2010-01-02', '2010-01-04']] are in the [index]" KeyError:“ [['2010-01-02','2010-01-04']]都不在[索引]中”
How can .loc
be used with dates in this context? .loc
如何在这种情况下与日期一起使用?
One possible solution is convert dates to DatetimeIndex
or to_datetime
and then it works nice: 一种可能的解决方案是将日期转换为DatetimeIndex
或to_datetime
,然后效果很好:
print (df.loc[pd.DatetimeIndex(['2010-01-02', '2010-01-04'])])
0 1 2
2010-01-02 0.827821 0.285281 0.781960
2010-01-04 0.872664 0.895636 0.368673
print (df.loc[pd.to_datetime(['2010-01-02', '2010-01-04'])])
0 1 2
2010-01-02 0.218419 0.806795 0.454356
2010-01-04 0.038826 0.741220 0.732816
You can use the boolean mask from isin
: 您可以使用isin
的布尔掩码:
In [151]:
df[df.index.isin(['2010-01-02', '2010-01-04'])]
Out[151]:
0 1 2
2010-01-02 0.939004 0.236200 0.495362
2010-01-04 0.254485 0.345047 0.273453
Unfortunately partial datetime string matching with a list won't work currently so either this or actual datetime values need to be passed 不幸的是,部分日期时间字符串与列表匹配目前无法正常工作,因此需要传递此日期时间或实际日期时间值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.