【问题标题】:Python Pandas Warning: A value is trying to be set on a copy of a slice from a DataFramePython Pandas 警告:试图在 DataFrame 中的切片副本上设置值
【发布时间】:2021-03-05 18:09:53
【问题描述】:

我有一个 Pandas DataFrame,我想使用以下代码更改列的所有值:

df["Population"] = round(df["Population"]/1000000,1)

我收到以下警告:

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
  return super().rename(
<ipython-input-6-59bf041bb022>:2: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  df["Population"] = round(df["Population"]/1000000,1)

什么是正确的方法来避免这种警告?

感谢您的帮助!

【问题讨论】:

    标签: python pandas warnings


    【解决方案1】:

    在你拥有你的 df 之前,它是一些其他数据框的子集

    df = alldf[cond].copy()
    

    或者我们试试assign

    df = df.assign(Population = round(df["Population"]/1000000,1))
    

    【讨论】:

    • 谢谢。您建议的解决方案 2 有效。尽管如此,我首先发现了错误发生的原因。我正在处理数据框的副本,因为在上一行中我将 df 分配给副本。感谢这篇文章stackoverflow.com/questions/33727667/…,我找到了解决方案
    • 这是了解潜在问题的宝贵资源:@​​987654322@
    猜你喜欢
    • 2016-06-16
    • 2016-12-22
    • 2019-03-30
    • 2016-02-17
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-23
    相关资源
    最近更新 更多