在 pandas 中使用 DataFrame.where 方法时出现 ValueError
ValueError when using the DataFrame.where method in pandas
我正在编写以下代码,我只想使用 pd.where
方法获取值的前 3 分钟,但出现以下错误:
ValueError:条件数组必须与 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)
有一个 another question 出现此错误,但上下文不同。
整数索引的代码似乎运行良好,但对于时间序列我有问题。
将df.index
转换为series
后可以使用df.where
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]
我正在编写以下代码,我只想使用 pd.where
方法获取值的前 3 分钟,但出现以下错误:
ValueError:条件数组必须与 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)
有一个 another question 出现此错误,但上下文不同。
整数索引的代码似乎运行良好,但对于时间序列我有问题。
将df.index
转换为series
后可以使用df.where
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]