改变一行pd中的一些值.DataFrame导致SettingWithCopyWarning



我正在制作股票应用程序,当获取数据并编辑它时,看到这个错误。
代码很简单:

df = yf.download(ticker, period=period, interval='1wk', auto_adjust=True, threads=True)

这里我得到DataFrame如下:

Open        High         Low       Close     Volume
Date                                                                 
2020-05-25  205.940002  207.880005  196.699997  207.389999  114231300
2020-06-01  205.899994  220.589996  203.940002  219.550003   85600600
2020-06-08  219.600006  225.000000  213.559998  217.639999   68520500
2020-06-15  214.110001  226.500000  212.750000  220.639999   77023000
2020-06-22  220.919998  231.029999  213.500000  215.710007   78020200
...                ...         ...         ...         ...        ...
2022-05-02   96.410004  102.690002   88.709999   90.050003   95662500
2022-05-09   86.955002   88.639999   78.010002   87.989998  115590500
2022-05-16   87.699997   94.480003   84.730003   86.790001  107750100
2022-05-23   87.059998   87.415001   81.540001   82.470001   29212600
2022-05-25   83.720001   84.070000   81.070000   82.309998   22781455

然后我需要编辑日期"2022-05-23">

df2 = df.loc[d_str] #d_str is 2022-05-25
df.loc[dtd2_s]['Close'] = df2['Close'] #dtd2_s is 2022-05-23

df.loc[dtd2_s]['High'] = max(df2['High'], df.loc[dtd2_s]['High'])
df.loc[dtd2_s]['Low'] = min(df2['Low'], df.loc[dtd2_s]['High'])

但是这里我得到SettingWithCopyWarning。

/Users/alex26/miniforge3/envs/rq/lib/python3.8/site-packages/pandas/core/series.py:1056: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
cacher_needs_updating = self._check_is_chained_assignment_possible()

你知道怎么修理它吗?


谢谢

您可能想尝试使用loc[]:

df2 = df.loc[d_str] #d_str is 2022-05-25
df.loc[dtd2_s, 'Close'] = df2['Close'] #dtd2_s is 2022-05-23
df.loc[dtd2_s, 'High'] = max(df2['High'], df.loc[dtd2_s]['High'])
df.loc[dtd2_s, 'Low'] = min(df2['Low'], df.loc[dtd2_s]['High'])

具体来说,我使用了loc[index_value, column_label]和一组大括号和逗号,而不是loc[index_value][column_label],它是对loc[]的单个调用,然后是对[]的链式调用,这可能会产生警告。

下面是显示上述loc[]用法的文档。

最新更新