2017-08-24 73 views
0

我正在编写下面的代码,并且我只想用pd.where方法获取值的前3分钟,但出现以下错误: ValueError:数组条件必须是相同的形状,自当在熊猫中使用DataFrame.where方法时出现ValueError

import pandas as pd 
import numpy as np 

index = pd.date_range(start = '2017-06-01 00:00', end='2017-06-01 01:00', freq='1min') 
values = np.arange(0, len(index)) 
df = pd.DataFrame(values, index = index) 

df.where(df.index <= df.index[0] + pd.DateOffset(minutes=3), np.nan) 

没有与此误差的another question但是上下文是不同的。

整数索引的代码似乎运作良好,但对于时间序列我有问题。

回答

1

可以转换df.indexseries

In [557]: df.where(df.index.to_series() <= df.index[0] + pd.DateOffset(minutes=3)) 
Out[557]: 
         0 
2017-06-01 00:00:00 0.0 
2017-06-01 00:01:00 1.0 
2017-06-01 00:02:00 2.0 
2017-06-01 00:03:00 3.0 
2017-06-01 00:04:00 NaN 
2017-06-01 00:05:00 NaN 
2017-06-01 00:06:00 NaN 
...     ... 
2017-06-01 00:57:00 NaN 
2017-06-01 00:58:00 NaN 
2017-06-01 00:59:00 NaN 
2017-06-01 01:00:00 NaN 

[61 rows x 1 columns] 
后使用 df.where