提问人:FluidMechanics Potential Flows 提问时间:10/27/2023 最后编辑:FluidMechanics Potential Flows 更新时间:10/27/2023 访问量:97
Pandas SettingWithCopyWarning 链接数据帧操作并在笔记本中显示时
Pandas SettingWithCopyWarning when chaining dataframe operations and displaying in Notebook
问:
磁共振:
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、和 .VSCode
Python 3.11.1
对于任何难以重现警告的人,您可以前往 https://colab.research.google.com/ 哪个并复制我的 MRE。它将显示错误:
答: 暂无答案
评论
pandas==2.1.0
print
repr
)