Wild Goat
Wild Goat

Reputation: 3579

Pandas: SettingWithCopyWarning Try using .loc

I know that this is a very popular error, however, in my case, I was not able to figure out why that happening to me.

I am getting:

 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
      df['time'] = pd.to_datetime(df['time'], unit='ms')
    : 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

code:

import pandas as pd
from pandas import DataFrame


def filter_df(df: DataFrame, symbol: str):
    return df.loc[(df['symbol'] == symbol)]


def convert_time(df):
    df['time'] = pd.to_datetime(df['time'], unit='ms')
    return df


df = pd.read_hdf(path_or_buf='/tmp/data/file.h5')
df = filter(df, 'AAA')
df = convert_time(df)

Could you please help me to figure out why I am getting such warning?

Upvotes: 3

Views: 3075

Answers (1)

00__00__00
00__00__00

Reputation: 5327

It is a well documented warning. To solve

df.loc[:,'time'] = pd.to_datetime(df['time'], unit='ms')

This happens because df['time'] is a view, not the real data you would like to edit. Please check elsewhere in the code as this warning will popup eveytime you assing a column like

   df[column_name]=something

The correct is

   df.loc[:, column_name]=something

Upvotes: 5

Related Questions