来自R,我天真地尝试
dfE_fitted['E_after'] = dfE_fitted['E_before']
那给了我
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
公平地说,我会尝试一下:
dfE_fitted.loc[:,'E_after'] = dfE_fitted['E_before']
这给了我
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/indexing.py:337: 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: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
self.obj[key] = _infer_fill_value(value)
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/indexing.py:517: 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: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
self.obj[item] = s
我在做什么可怕的错误?
最佳答案
这不是你如何完成你的任务。这就是您构建 dfE_fitted
的方式。你以这样的方式构建它,以便成为其他东西的“副本”。建议使用 .loc
旨在用于构建 dfE_fitted
。即便如此,使用 .loc
也不能保证。使用 .loc
后,您仍然可以拥有“is_copy”标志
但是,我看不出你是怎么做到的。我能做的就是建议你这样做
dfE_fitted = dfE_fitted.copy()
这将解开“复制”关系,您可以按原样继续分配。
dfE_fitted['E_after'] = dfE_fitted['E_before']
工作示例
df = pd.DataFrame(dict(A=[1, 2], E_before=[3, 4], E_after=[5, 6]))
# Notice how I constructed this
dfE_fitted = df[['E_before']]
然后我试试
dfE_fitted['E_after'] = dfE_fitted['E_before']
我得到
但是,我是否像这样构建了
dfE_fitted
:# Notice I used `.loc` like what was recommended
dfE_fitted = df.loc[:, ['E_before']]
我可以在没有警告的情况下执行以下操作:
dfE_fitted['E_after'] = dfE_fitted['E_before']
您可以通过查看其
is_copy
属性来判断数据帧是否是“副本”。如果是副本,它将返回一个<weakref at 0x1188d94f8; to 'DataFrame' at 0x1184bf898>
其计算结果为
True
bool(dfE_fitted.is_copy)
True
否则,如果它不是“副本”,则它是
None
并计算为 False
关于python - 尽管遵循 .loc 建议,但创建新列仍会引发 Pandas 错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46347732/