Pandas SettingWithCopyWarning 链接数据帧操作并在笔记本中显示时

Pandas SettingWithCopyWarning when chaining dataframe operations and displaying in Notebook

提问人:FluidMechanics Potential Flows 提问时间:10/27/2023 最后编辑:FluidMechanics Potential Flows 更新时间:10/27/2023 访问量:97

问:

磁共振:

import pandas as pd

# Sample data for demonstration
data = {
    "a": ["a", "b", "b", "a", "b", "b", "a", "a"],
    "date": ["01/01/2021", "02/01/2021", "03/01/2021", "04/01/2021", "05/01/2021", "06/01/2021", "07/01/2021", "08/01/2021"]
}

df = pd.DataFrame(data)

# CELL 1
# Delete duplicates
print(df.duplicated().sum())
df = df.drop_duplicates()
df  # Displaying the dataframe. In a Jupyter-like environment, this will print the dataframe.

# CELL 2
# Filter out certain values from "a"
print(df["a"].value_counts())
df = df[df["a"].isin(["b"])]

# CELL 3
# Convert "date" to datetime
df["date"] = pd.to_datetime(df["date"], dayfirst=True)

在 Jupyter Notebook 中按顺序执行上述单元格时,我在单元格 3 中收到 SettingWithCopyWarning。奇怪的是,如果我删除单元格 1 末尾的(显示命令),我不会收到警告。df

我知道该警告是为了提醒用户在修改视图与副本上的数据时存在潜在陷阱,但我不确定为什么显示数据帧会触发此警告。有人可以解释这种行为背后的原因并提出一种干净的方法来解决它吗?

我正在使用 Windows 11、和 .VSCodePython 3.11.1

对于任何难以重现警告的人,您可以前往 https://colab.research.google.com/ 哪个并复制我的 MRE。它将显示错误:enter image description here

Python pandas 数据帧 jupyter-notebook

评论

0赞 mozway 10/27/2023
没有警告我,你用的是哪个熊猫版本?
1赞 user19077881 10/27/2023
我使用 Notebook、Pandas 2.1.1 和如上所述的单元格布局收到此警告。也很奇怪 - 如果您将 df 更改为 print(df),则不会出现错误消息。奇怪!据推测,Jupyter 的一些怪癖,因为单元格 3 语句无论如何都不应该发出警告。
0赞 FluidMechanics Potential Flows 10/27/2023
我正在使用 .很抱歉没有将其包含在最初的帖子@mozway中。pandas==2.1.0
0赞 mozway 10/27/2023
我无法用几个熊猫版本复制
1赞 Corralien 10/27/2023
我可以用 Google Colab 重现您的问题!!您的代码适用于 python/ipython 控制台。我想 Jupyter Notebook 或 Google Colab 会修改一些东西以获得漂亮的数据表(不像printrepr)

答: 暂无答案