如何解决Python脚本中的SettingWithCopyWarning警告?
Pandas SettingWithCopyWarning 解决方法
我是Python新手,正在通过yfinance示例项目学习Python。运行以下脚本时出现SettingWithCopyWarning警告,查阅多篇相关文章后仍无法解决,恳请技术指导。
代码示例
# 设置感兴趣的时间范围 net_historical = net.history(start="2020-01-02", end="2022-10-21", interval="1d") # 创建新的DataFrame signals,仅保留Date和Close列 #print(signals_df) signals_df = net_historical.drop(columns=['Open', 'High', 'Low', 'Volume','Dividends', 'Stock Splits']) signals_df = signals_df.copy() # 设置短期和长期窗口 short_window = 50 long_window = 100 # 生成短期和长期移动平均线(分别为50日和100日) signals_df['SMA50'] = signals_df['Close'].rolling(window=short_window).mean() signals_df['SMA100'] = signals_df['Close'].rolling(window=long_window).mean() signals_df['Signal'] = 0.0 signals_df['Symbol'] = line_strip # 生成交易信号0或1: # 当SMA50低于SMA100时为0,当SMA50高于(或交叉超过)SMA100时为1 signals_df['Signal'][short_window:] = np.where( signals_df['SMA50'][short_window:] > signals_df['SMA100'][short_window:], 1.0, 0.0 )
警告信息
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy signals_df['Signal'][short_window:] = np.where( /var/folders/xj/401632wd1qx7h6t0kqfjl98m0000gn/T/ipykernel_14492/214794330.py:59: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
解决方法
这个警告是因为使用了链式索引(signals_df['Signal'][short_window:])赋值,Pandas无法判断你操作的是原DataFrame还是它的副本,因此抛出警告。
直接改用Pandas官方推荐的.loc索引方式即可解决:
将原赋值代码替换为:
signals_df.loc[short_window:, 'Signal'] = np.where( signals_df.loc[short_window:, 'SMA50'] > signals_df.loc[short_window:, 'SMA100'], 1.0, 0.0 )
.loc通过行标签+列标签的组合明确指定操作区域,消除了副本/视图的歧义,自然就不会触发这个警告了。
内容的提问来源于stack exchange,提问作者chorink65
相关产品推荐
相关产品推荐

