Why does one use of iloc() give a SettingWithCopyWarning, but the other doesn't?

后端 未结 3 596
隐瞒了意图╮
隐瞒了意图╮ 2021-01-14 10:09

Inside a method from a class i use this statement:

self.__datacontainer.iloc[-1][\'c\'] = value

Doing this i get a \"SettingWithCopyWarnin

3条回答
  •  自闭症患者
    2021-01-14 10:35

    So it's pretty hard to answer this without context around your problem operation, but the pandas documentation covers this pretty well.

    >>> df[['C']].iloc[0] = 2 # This is a problem
    SettingWithCopyWarning: 
    A value is trying to be set on a copy of a slice from a DataFrame
    

    Basically it boils down to - don't chain together indexing operations if you can just use a single operation to do it.

    >>> df.loc[0, 'C'] = 2 # This is ok
    

    The warning you're getting is because you've failed to set a value in the original dataframe that you're presumably trying to modify - instead, you've copied it and set something into the copy (usually when this happens to me I don't even have a reference to the copy and it just gets garbage collected, so the warning is pretty helpful)

提交回复
热议问题