正如argrelextrema 指出的那样,返回相对极值的索引。
使用这些索引将 index 直接放入与原始 DataFrame 形状相同的布尔数组中:
import numpy as np
import pandas as pd
from scipy.signal import argrelextrema
# for reproducibility
np.random.seed(42)
# create toy DataFrame
df = pd.DataFrame(data=np.random.random((100, 3)) * 20, columns=["AAPL", "MSFT", "TSLA"])
# extract rows and cols indices using extrema
rows, cols = argrelextrema(df.values, np.greater, axis=0,order=1)
# create boolean numpy array
values = np.zeros_like(df.values, dtype=bool)
# set the values of the extrema to True
values[rows, cols] = True
# convert to DataFrame
result = pd.DataFrame(data=values, columns=df.columns)
print(result)
输出
AAPL MSFT TSLA
0 False False False
1 False False True
2 False False False
3 False True True
4 False False False
.. ... ... ...
95 False False False
96 True False True
97 False False False
98 True True True
99 False False False
[100 rows x 3 columns]
上面代码的重要部分是这样的:
# create boolean numpy array
values = np.zeros_like(df.values, dtype=bool)
# set the values of the extrema to True
values[rows, cols] = True
作为替代方案,您可以直接从sparse.csr_matrix 构建values 数组:
from scipy.sparse import csr_matrix
values = csr_matrix((np.ones(rows.shape), (rows, cols)), shape=df.shape, dtype=bool).toarray()