在 Pandas 中使用 DataFrame.where 方法时出现 ValueError

mk_*_*sch 3 python datetime where dataframe pandas

我正在编写以下代码,我只想使用pd.where方法获取值的前 3 分钟,但出现以下错误:ValueError: Array conditional must be same shape as self

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)
Run Code Online (Sandbox Code Playgroud)

此错误还有另一个问题,但上下文不同。

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

Zer*_*ero 5

您可以使用df.where转换后df.index,以series

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]
Run Code Online (Sandbox Code Playgroud)