为什么我在 Pandas 数据帧中收到“SettingWithCopyWarning”,我该如何解决?

Why am I getting a 'SettingWithCopyWarning' in my Pandas dataframe and how do I fix it?

提问人:mle 提问时间:5/24/2023 更新时间:5/25/2023 访问量:53

问:

使用 Pandas 设置 WithCopyWarning

在阅读了大部分文档(包括警告链接)后,我继续遇到此警告:https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy

以及以下问题:

如何处理 Pandas 中的 SettingWithCopyWarning

将 Pandas 列转换为 DateTime

我正在努力学习 Python,但我很难真正让这条警告消息消失。我也在努力使用较小的假数据来复制这个问题,但我复制问题的失败尝试如下。

在这个小示例中,我没有获得 SettingWithCopyWarning,但每次我尝试在我的完整数据帧上运行相同的代码(使用 30K 模拟 VIN 和车辆数据)时,我都会得到 SettingWithCopyWarning。我已经阅读了有关链式索引的文章,并了解它有问题。不幸的是,我不明白链式索引何时导致问题(即,您何时获得视图与副本,以及在我包含的示例中,以下哪些符号实际上是链式索引?感谢您对这个令人沮丧的话题的任何建议。

import pandas as pd

vin_dat = pd.DataFrame({'vin' : [1, 2, 3, 4, 5],
    'purchase_date' : ["2020-03-26", "2021-04-05", "2021-12-17", "2021-12-18", "2022-01-30"],
    'nvlw_end_date' : ["2023-03-26", "2024-04-05", "2024-12-17", "2024-12-18", "2025-01-30"] })

vin_dat.loc[:, ("purchase_date", "nvlw_end_date")] = vin_dat.loc[:, ("purchase_date", "nvlw_end_date")].copy().apply(pd.to_datetime)
# DeprecationWarning: In a future version, `df.iloc[:, i] = newvals` will attempt to set the values inplace instead of always setting a new array.

vin_dat[["purchase_date", "nvlw_end_date"]] = vin_dat[["purchase_date", "nvlw_end_date"]].apply(pd.to_datetime)
# This works without an error on this sample, but gives me a SettingWithCopyWarning on my larger dataset

vin_dat['purchase_date'] = vin_dat['purchase_date'].apply(pd.to_datetime) 
# This works without an error on this sample, but gives me a SettingWithCopyWarning on my larger dataset

vin_dat['nvlw_end_date'] = pd.to_datetime(vin_dat['nvlw_end_date'])
# This works without an error on this sample, but gives me a SettingWithCopyWarning on my larger dataset
熊猫 设置与复制警告

评论

0赞 Learning is a mess 5/24/2023
您较大的数据集有多大?是相同的dtypes吗?
0赞 mle 5/25/2023
我较大的数据集是 30,000 个 VIN,我只是将 VIN 设置为整数而不是长字符串,因此数据类型应该相同。如果您有兴趣查看我模拟数据的 Git 存储库,它位于:github.com/emilysheen/reliabilityAnalysis。我自己模拟了数据,然后做了一些绘图,现在我正在尝试进行一些统计建模。我认为尽管有警告,但数据是正确的,但我非常沮丧,我不断遇到警告,试图遵循良好的编码形式。

答:

0赞 Learning is a mess 5/25/2023 #1

不是真正的答案,但我需要使用这个空间来分享屏幕截图。我无法使用您指向我的数据文件重现警告,请参阅:

enter image description here

我们是否使用相同的数据?相同的熊猫版本?