gpt4 book ai didi

python - Pandas :SettingWithCopyWarning 尝试使用 .loc

转载 作者:行者123 更新时间:2023-12-04 03:01:05 24 4
gpt4 key购买 nike

我知道这是一个非常常见的错误,但是,就我而言,我无法弄清楚为什么会发生这种情况。

我得到:

 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)

你能帮我弄清楚为什么我会收到这样的警告吗?

最佳答案

这是一个有据可查的警告。解决

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

发生这种情况是因为 df['time'] 是一个 View ,而不是您想要编辑的真实数据。请检查代码中的其他地方,因为每次您访问像这样的列时都会弹出此警告

   df[column_name]=something

正确的是

   df.loc[:, column_name]=something

关于python - Pandas :SettingWithCopyWarning 尝试使用 .loc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49181661/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com