Pandas:SettingWithCopyWarning尝试使用.loc

时间:2018-03-08 20:11:10

标签: python pandas

我知道这是一个非常受欢迎的错误,但在我的情况下,我无法弄清楚为什么会发生这种情况。

我得到了:

 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

代码:

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)

请你帮我弄明白为什么我会收到这样的警告?

1 个答案:

答案 0 :(得分:3)

这是一个记录良好的警告。 解决

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

这是因为df['time']是一个视图,而不是您想要编辑的真实数据。 请检查代码中的其他位置,因为此警告将弹出您指定

列的eveytime
   df[column_name]=something

正确的是

   df.loc[:, column_name]=something