pandas :SettingWithCopyWarning: [英] Pandas: SettingWithCopyWarning:
问题描述
我尝试了以下代码将列转换为日期":
I tried the following code to convert a column to "date":
df.['DATE'] = pd.to_datetime(df['DATE'])
或
df.DATE = pd.to_datetime(df.DATE)
但出现以下错误:
/Users/xyz/anaconda3/envs/sensor/lib/python3.6/site-packages/pandas/core/indexing.py:517: SettingWithCopyWarning:试图在一个副本上设置一个值 从DataFrame切片.尝试使用.loc [row_indexer,col_indexer] = 值代替
/Users/xyz/anaconda3/envs/sensor/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
请参阅文档中的警告: http://pandas.pydata.org/pandas -docs/stable/indexing.html#indexing-view-versus-copy self.obj [item] = s
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy self.obj[item] = s
我将代码更改为以下内容:
I changed the code to the following:
df.loc[:,'DATE'] = pd.to_datetime(df.loc[:,'DATE'])
但我仍然遇到相同的错误.
but I still get the same error.
与此相同
for i in df.index:
df.loc[i,'DATE'] = pd.to_datetime(df.loc[i,'DATE'])
推荐答案
You need add copy
:
df = data.loc[data.ID == 79]
收件人:
df = data.loc[data.ID == 79].copy()
如果稍后在df
中修改值,您会发现修改不会传播回原始数据(data
),并且Pandas会发出警告.
If you modify values in df
later you will find that the modifications do not propagate back to the original data (data
), and that Pandas does warning.
这篇关于 pandas :SettingWithCopyWarning:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!