首页 > 编程问答 >返回视图与副本。尝试在 DataFrame 的切片副本上设置一个值。尝试使用 .loc[row_indexer,col_indexer] = value ins

返回视图与副本。尝试在 DataFrame 的切片副本上设置一个值。尝试使用 .loc[row_indexer,col_indexer] = value ins

时间:2024-07-30 11:33:34浏览次数:9  
标签:python pandas yfinance

我从雅虎财经 (yfinance) 下载了有关股票交易价格和交易量的数据。然后我创建了 Closes 数据框,其中包含收盘价和成交量的数据(我删除了不必要的信息)。然后我想将列添加到 Closes 数据框中,并计算年、季度、月和周的平均交易量。但在执行代码时,会出现警告“正在尝试在 DataFrame 切片的副本上设置值。请尝试使用 .loc[row_indexer,col_indexer] = value 代替”。我读了这篇文章“https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy”,但我不明白我应该做什么我的情况。我希望消除警告,并在添加的列中正确处理计算。 如何解决此警告(不是忽略它,而是修复它)?

import yfinance as yf
import pandas as pd
import warnings
warnings.filterwarnings("ignore", message="The 'unit' keyword in TimedeltaIndex construction is deprecated and will be removed in a future version. Use pd.to_timedelta instead.", category=FutureWarning, module="yfinance.utils")
warnings.filterwarnings("ignore", category=pd.errors.PerformanceWarning)
#warnings.filterwarnings("ignore", message="DataFrame is highly fragmented.  This is usually the result of calling `frame.insert` many times, which has poor performance.  Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`", category=pd.errors.PerformanceWarning)

TickersList=['A', 'AAL', 'AAPL', 'ABBV', 'ABNB', 'ABT', 'ACGL', 'ACN', 'ADBE', 'ADI', 'ADM']
Stocks=yf.download(TickersList[0::1], period="1y", interval="1d", group_by='ticker')
Stocks.sort_index(level=0,axis=1,inplace=True)
Closes=Stocks.loc[:, (slice(None), ['Close', 'Volume'])]
for i in Closes.columns.get_level_values(0): 
    Closes.loc[:,(i,'Meam1Y')]=Closes.loc[:,(i,'Volume')].rolling (250).mean() 
    Closes.loc[:,(i,'Meam1Q')]=Closes.loc[:,(i,'Volume')].rolling (62).mean() 
    Closes.loc[:,(i,'Meam1M')]=Closes.loc[:,(i,'Volume')].rolling (20).mean() 
    Closes.loc[:,(i,'Meam1W')]=Closes.loc[:,(i,'Volume')].rolling (5).mean() 
Closes

警告全文:

请参阅文档中的警告: https://pandas.pydata.org/pandas-docs/ stable/user_guide/indexing.html#returning-a-view-versus-a-copy Closes.loc[:,(i,'Meam1Y')]=Closes.loc[:,(i,'Volume') ].滚动(250).mean() C:\ Users \ iiiva \ AppData \ Local \ Temp \ ipykernel_27188 \ 26776804.py:4:SettingWithCopyWarning: 尝试在 DataFrame 的切片副本上设置一个值。 尝试使用 .loc[row_indexer,col_indexer] = value 代替


这个警告之所以出现是因为你试图在一个可能是 DataFrame 视图的对象上进行修改。你遇到的问题在于,当你执行 Closes.loc[:, (i, 'Volume')] 时,你并不能保证这会返回 DataFrame 的视图还是副本。如果是副本,修改不会反映到原始 DataFrame 中。

以下是如何修改代码来避免此警告并确保将新列添加到 Closes DataFrame 中:

import yfinance as yf
import pandas as pd

# ... (你现有的代码来下载和准备数据)

for i in Closes.columns.get_level_values(0):
    # 使用 .loc 直接分配给新的列
    Closes.loc[:, (i, 'Meam1Y')] = Closes[(i, 'Volume')].rolling(250).mean()
    Closes.loc[:, (i, 'Meam1Q')] = Closes[(i, 'Volume')].rolling(62).mean()
    Closes.loc[:, (i, 'Meam1M')] = Closes[(i, 'Volume')].rolling(20).mean()
    Closes.loc[:, (i, 'Meam1W')] = Closes[(i, 'Volume')].rolling(5).mean()

Closes

解释:

  1. 直接赋值: 我们使用 Closes.loc[:, (i, 'NewColumnName')] = ... 来直接在 Closes DataFrame 上创建和分配新的列。这确保了修改会反映到原始 DataFrame 上。

通过这个修改,你应该能够避免警告,并且计算出的移动平均线将正确存储在 Closes DataFrame 中。

标签:python,pandas,yfinance
From: 78809707

相关文章

  • vscode python 3.7 pylance debugpy 插件 vsix
    可能报错  crashed5timesinthelast3minutes.Theserverwillnotberestarted.  ---pylance 可能报错  cannotreadpropertiesofundefinedreadingresolveEnvironment   --- debugger可能      vscodepython3.7调试没有反应......
  • Python获取秒级时间戳与毫秒级时间戳的方法[通俗易懂]
    参考资料:https://cloud.tencent.com/developer/article/21581481、获取秒级时间戳与毫秒级时间戳、微秒级时间戳代码语言:javascript复制importtimeimportdatetimet=time.time()print(t)#原始时间数据print(int(t))......
  • CEFPython
    在Tkinter界面中直接嵌入Selenium的浏览器视图并不是一件直接的事情,因为Selenium本身并不提供图形界面嵌入的功能。Selenium主要用于自动化web浏览器,但它并不直接控制浏览器窗口的显示方式,而是依赖于WebDriver来与浏览器交互。然而,你可以使用一些替代方案来在Tkinter应用中模拟或......
  • 《最新出炉》系列初窥篇-Python+Playwright自动化测试-58 - 文件下载
    1.简介前边几篇文章讲解完如何上传文件,既然有上传,那么就可能会有下载文件。因此宏哥就接着讲解和分享一下:自动化测试下载文件。可能有的小伙伴或者童鞋们会觉得这不是很简单吗,还用你介绍和讲解啊,不说就是访问到下载页面,然后定位到要下载的文件的下载按钮后,点击按钮就可以了。其实......
  • Python - Function Annotations
     deffunc(s:str,i:int,j:int)->str:returns[i:j]Theparametersissupposedtobeastring,soweplaceacolonaftertheparameternameandthenwritestr.Parametersiandjaresupposedtobeintegerssowewriteintforthem.Returntypeis......
  • 使用带有 pythonKit XCODE 的嵌入式 Python,在 iOS 应用程序中与 OpenCV-python 签名不
    我根据Beewares使用指南在XCODE中将Python嵌入到我的iOS项目中https://github.com/beeware/Python-Apple-support/blob/main/USAGE.md运行时,我得到pythonKit找不到由ultralytics导入的cv2错误。当我将OpenCV-python添加到我的app_packages文件夹时......
  • Python - Arguments and Parameters
    ParametersinFunctionDefinitionA.deffunc(name):MatchbypositionorbynameB.deffunc(name=value):DefaultargumentC.deffunc(*args):CollectextrapositionalargumentsintuplenamedargsD.deffunc(**kwargs):Collectextrakeywordargumentsi......
  • Python MySQL 无法连接,原因不明
    当我尝试使用python连接到我的MySQL数据库时,由于未知原因显示错误:dTraceback(mostrecentcalllast):File"/usr/local/bin/flask",line8,in<module>sys.exit(main())^^^^^^File"/usr/local/lib/python3.12/site-packages/flask/cli.py&......
  • 基于Python Django的旅游景点数据分析与推荐系统
    基于PythonDjango的旅游景点数据分析与推荐系统。源码+数据库+文档(LW)。开发技术:Pythondjangomysql。项目内容:系统包括多个功能模块,涵盖了用户管理、旅游景点管理、管理员管理、系统管理等方面,以及一些其他辅助功能和信息展示模块。用户管理模块允许管理员管理系统中的用......
  • django基于Python的校园个人闲置物品换购平台
    django基于Python的校园个人闲置物品换购平台。源码+数据库+文档(lw+ppt)。开发技术:Pythondjangomysql。项目内容:系统主要包括主页、个人中心、用户管理、景点信息管理、系统管理等功能。    ......