使用Pandas cummin函数结果恒为0的技术求助
问题:Pandas cummin()计算累计最小值结果全为0,cummax()正常
我用Pandas的cummin()函数计算close列的累计最小值时,结果始终显示为0,但cummax()可以正常工作。
我的代码:
df = pd.DataFrame(df, columns=['symbol', 'timestamp', 'open', 'high', 'low', 'close', 'volume']) df["min_Close"] = df.close.shift(fill_value=0).cummin() df["max_Close"] = df.close.shift(fill_value=0).cummax() print(df)
原始DataFrame:
symbol timestamp open high low close volume 0 AAVEUSDT 1663186500000 81.70 81.90 81.65 81.80 405.54 1 AAVEUSDT 1663186800000 81.80 81.85 81.70 81.75 233.11 2 AAVEUSDT 1663187100000 81.75 82.05 81.75 81.75 346.30 3 AAVEUSDT 1663187400000 81.75 81.90 81.60 81.90 126.11 4 AAVEUSDT 1663187700000 81.90 81.95 81.70 81.75 260.90 5 AAVEUSDT 1663188000000 81.75 81.75 81.60 81.65 274.26
运行结果:
symbol timestamp open high low close volume min_Close max_Close 0 AAVEUSDT 1663186500000 81.70 81.90 81.65 81.80 405.54 0.0 0.00 1 AAVEUSDT 1663186800000 81.80 81.85 81.70 81.75 233.11 0.0 81.80 2 AAVEUSDT 1663187100000 81.75 82.05 81.75 81.75 346.30 0.0 81.80 3 AAVEUSDT 1663187400000 81.75 81.90 81.60 81.90 126.11 0.0 81.80 4 AAVEUSDT 1663187700000 81.90 81.95 81.70 81.75 260.90 0.0 81.90 5 AAVEUSDT 1663188000000 81.75 81.75 81.60 81.65 274.26 0.0 81.90
原因分析
你在shift()时给第一行填充了0,而0比所有close列的数值都小。cummin()是从第一个值开始累计取最小值,所以后续所有行的累计最小值都会保持0;而cummax()会在遇到比0大的数值时更新,所以能正常显示正确的累计最大值。
解决方案
根据你的需求,有两种调整方式:
1. 计算截至当前行的所有close的累计最小值(含当前行)
如果不需要移位,直接计算从第一行开始的累计最小值:
df["min_Close"] = df.close.cummin() df["max_Close"] = df.close.cummax()
运行后结果:
symbol timestamp open high low close volume min_Close max_Close 0 AAVEUSDT 1663186500000 81.70 81.90 81.65 81.80 405.54 81.80 81.80 1 AAVEUSDT 1663186800000 81.80 81.85 81.70 81.75 233.11 81.75 81.80 2 AAVEUSDT 1663187100000 81.75 82.05 81.75 81.75 346.30 81.75 81.80 3 AAVEUSDT 1663187400000 81.75 81.90 81.60 81.90 126.11 81.75 81.90 4 AAVEUSDT 1663187700000 81.90 81.95 81.70 81.75 260.90 81.75 81.90 5 AAVEUSDT 1663188000000 81.75 81.75 81.60 81.65 274.26 81.65 81.90
2. 计算当前行之前所有close的累计最小值(不含当前行)
如果需要保留移位逻辑,即每一行的min_Close是之前所有行的close最小值,不要用0填充,而是用第一个close值或者NaN再处理:
# 方式一:用第一个close值填充移位后的空值 df["min_Close"] = df.close.shift(fill_value=df.close.iloc[0]).cummin() df["max_Close"] = df.close.shift(fill_value=df.close.iloc[0]).cummax() # 方式二:用NaN填充,再手动设置第一行的初始值 df["min_Close"] = df.close.shift().cummin() df["max_Close"] = df.close.shift().cummax() df.loc[0, ["min_Close", "max_Close"]] = df.close.iloc[0]
处理后结果:
symbol timestamp open high low close volume min_Close max_Close 0 AAVEUSDT 1663186500000 81.70 81.90 81.65 81.80 405.54 81.80 81.80 1 AAVEUSDT 1663186800000 81.80 81.85 81.70 81.75 233.11 81.80 81.80 2 AAVEUSDT 1663187100000 81.75 82.05 81.75 81.75 346.30 81.75 81.80 3 AAVEUSDT 1663187400000 81.75 81.90 81.60 81.90 126.11 81.75 81.80 4 AAVEUSDT 1663187700000 81.90 81.95 81.70 81.75 260.90 81.75 81.90 5 AAVEUSDT 1663188000000 81.75 81.75 81.60 81.65 274.26 81.75 81.90
内容的提问来源于stack exchange,提问作者One boy
相关产品推荐
相关产品推荐

