我要创建一个新列,并在第一列上计算最大值,如下所示:
High Highest2P Highest3P
0 101.0 102.0 103.0
1 102.0 103.0 109.0
2 103.0 109.0 109.0
3 109.0 109.0
4 100.0
from pandas import *
df = pd.DataFrame({
"High": pd.Series( [101.0, 102.0, 103.0, 109.0, 100.0] )
})
def calcHighest2P(x): return max(df["High"], df["High"].shift(-1))
def calcHighest3P(x): return max(df["High"], df["High"].shift(-1), df["High"].shift(-2))
df["Highest2P"] = calcHighest2P(df["High"])
df["Highest3P"] = calcHighest3P(df["High"])
但是我收到以下错误消息:“ ValueError:系列的真值不明确。请使用a.empty,a.bool(),a.item(),a.any()或a.all( )。”
答案 0 :(得分:1)
您可以将Rolling.max
与assign
一起使用:
df.assign(**{
f'Highest{i}P': pd.Series(df.High.rolling(i).max().dropna().values)
for i in range(2, 4)}
)
High Highest2P Highest3P
0 101.0 102.0 103.0
1 102.0 103.0 109.0
2 103.0 109.0 109.0
3 109.0 109.0 NaN
4 100.0 NaN NaN