Pandas 替换数据帧时间序列中的值

Pandas replace values in dataframe timeseries

我有一个 pandas 数据帧 df,其中 pandas.tseries.index.DatetimeIndex 作为索引。

数据是这样的:

Time                 Open  High Low   Close Volume
2007-04-01 21:02:00 1.968 2.389 1.968 2.389 18.300000
2007-04-01 21:03:00 157.140 157.140 157.140 157.140 2.400000

.....

我想替换一个数据点,让 2.389 列中的第 2.389 天用 NaN 关闭:

In: df["Close"].replace(2.389, np.nan)
Out: 2007-04-01 21:02:00      2.389
     2007-04-01 21:03:00    157.140

替换没有将 2.389 更改为 NaN。怎么了?

您需要将结果分配给 df['Close'] 或传递参数 inplace=True : df['Close'].replace(2.389, np.NaN, inplace=True)

例如:

In [5]:

df['Close'] = df['Close'].replace(2.389, np.NaN)
df['Close']
Out[5]:
0      2.389
1    157.140
Name: Close, dtype: float64

大多数 pandas 操作 return 一个副本,一些接受参数 inplace

查看文档:http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.replace.html#pandas.Series.replace

replace 可能不适用于浮点数,因为您在 DataFrame 的 repr 中看到的浮点 表示 可能与底层的不一样漂浮。例如,实际收盘价可能是:

In [141]: df = pd.DataFrame({'Close': [2.389000000001]})

然而 df 的 repr 看起来像:

In [142]: df
Out[142]: 
   Close
0  2.389

因此,与其检查浮点数是否相等,通常最好检查是否接近:

In [150]: import numpy as np
In [151]: mask = np.isclose(df['Close'], 2.389)

In [152]: mask
Out[152]: array([ True], dtype=bool)

然后您可以使用布尔掩码 select 并更改所需的值:

In [145]: df.loc[mask, 'Close'] = np.nan

In [146]: df
Out[146]: 
   Close
0    NaN