【发布时间】:2017-02-08 00:50:57
【问题描述】:
在更改从另一个数据帧的切片创建的数据帧时,我是否应该始终使用 .copy() 方法显式生成副本?否则,我会收到 SettingWithCopy 警告。但是,在这种情况下,它并没有导致任何麻烦;原始数据框未更改。
>>> import pandas as pd
>>> df = pd.DataFrame([[6,3,2],[4,3,2],[5,4,2],[4,3,5]], columns=['a', 'b', 'c'])
>>> df
a b c
0 6 3 2
1 4 3 2
2 5 4 2
3 4 3 5
>>> df2 = df.loc[df.a<6, :]
>>> df2.loc[df2.b==3, 'b'] = 99
/usr/lib/python3/dist-packages/pandas/core/indexing.py:117: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
self._setitem_with_indexer(indexer, value)
__main__:1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
>>> df
a b c
0 6 3 2
1 4 3 2
2 5 4 2
3 4 3 5
>>> df2
a b c
1 4 99 2
2 5 4 2
3 4 99 5
或者,如果我执行以下操作,我不会收到任何警告。
>>> df2 = df.loc[df.a<6, :].copy()
>>> df2.loc[df2.b==3, 'b'] = 99
>>> df2
a b c
1 4 99 2
2 5 4 2
3 4 99 5
>>> df
a b c
0 6 3 2
1 4 3 2
2 5 4 2
3 4 3 5
后者更好吗? (因此我没有收到警告)。凭什么?是因为我确信 df2 是副本,因此无法更改原始数据帧 df?
【问题讨论】:
-
您确定这两个选项的作用完全相同吗?
-
好吧,
df2将99插入到两个实现的正确位置。这是你的意思吗?
标签: python python-3.x pandas