提问人:mle 提问时间:5/24/2023 更新时间:5/25/2023 访问量:53
为什么我在 Pandas 数据帧中收到“SettingWithCopyWarning”,我该如何解决?
Why am I getting a 'SettingWithCopyWarning' in my Pandas dataframe and how do I fix it?
问:
使用 Pandas 设置 WithCopyWarning
在阅读了大部分文档(包括警告链接)后,我继续遇到此警告:https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
以及以下问题:
如何处理 Pandas 中的 SettingWithCopyWarning
我正在努力学习 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
答:
评论