【问题标题】:Python - Getting "SettingWithCopyWarning" despite using df.locPython - 尽管使用了 df.loc,但仍获得“SettingWithCopyWarning”
【发布时间】:2021-04-15 10:25:45
【问题描述】:

尽管使用了推荐的方法,但我得到了 SettingWithCopyWarning。我错过了什么?我应该如何更正或取消此特定警告?

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.randint(1,100, size=(6,4)), columns=list('abcd'))
print(df)
#>     a   b   c   d
#> 0  25  76  90  82
#> 1   2  19  97  44
#> 2  52  36  96  26
#> 3  37  48  55  49
#> 4  54  98  71  99
#> 5  42  26  86  76

var = ('a b').split()
print(var)
#> ['a', 'b']
df2 = df[var]
print(df2)
#>     a   b
#> 0  25  76
#> 1   2  19
#> 2  52  36
#> 3  37  48
#> 4  54  98
#> 5  42  26

df2.loc[:,'e'] = pd.Series(df.a/df.d*100)
#> C:\Users\Rahul\anaconda3\lib\site-packages\pandas\core\indexing.py:1596: 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
#>   self.obj[key] = _infer_fill_value(value)
#> C:\Users\Rahul\anaconda3\lib\site-packages\pandas\core\indexing.py:1745: 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
#>   isetter(ilocs[0], value)
print(df2)
#>     a   b           e
#> 0  25  76   30.487805
#> 1   2  19    4.545455
#> 2  52  36  200.000000
#> 3  37  48   75.510204
#> 4  54  98   54.545455
#> 5  42  26   55.263158

reprexpy package于 2021-01-10 创建

【问题讨论】:

    标签: python pandas dataframe warnings


    【解决方案1】:

    使用以下代码创建第二个数据框:

    # create subset
    df2 = df[var].copy()
    
    # create new column
    df2['e'] = df.a/df.d*100
    df2
    #     a   b           e
    # 0  19  20   25.333333
    # 1  52  36  400.000000
    # 2   7  62   53.846154
    # 3   5  93    7.575758
    # 4  69  32  215.625000
    # 5  55  36   59.782609
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多