简体   繁体   中英

Pandas: SettingWithCopyWarning:

I tried the following code to convert a column to "date":

df.['DATE'] =  pd.to_datetime(df['DATE'])

or

df.DATE =  pd.to_datetime(df.DATE)

but I get the following error:

/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

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.

same with this

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]

to:

df = data.loc[data.ID == 79].copy()

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.

The problem is in the code you have not shown us. Somewhere, you have done something like this:

df = other.loc[something]

That is the root cause of this error message. You need to assign using .loc or similar directly into the original DataFrame:

other.loc[something, 'DATE'] = whatever

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM