Python - 获取“SettingWithCopyWarning"尽管使用 df.loc [英] Python - Getting "SettingWithCopyWarning" despite using df.loc
本文介绍了Python - 获取“SettingWithCopyWarning"尽管使用 df.loc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尽管使用了推荐的方法,我还是收到了 SettingWithCopyWarning.我错过了什么?我该如何更正或取消此特定警告?
I am getting the SettingWithCopyWarning despite using the recommended method. What am I missing? How shall I correct it or suppress this particular warning?
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 包 于 2021 年 1 月 10 日创建
Created on 2021-01-10 by the reprexpy package
推荐答案
使用以下代码创建第二个数据框:
Create the 2nd dataframe with the following code :
# 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
这篇关于Python - 获取“SettingWithCopyWarning"尽管使用 df.loc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文