Python:根据条件尝试将值设置为True时,SettingWithCopyWarning

问题描述 投票:1回答:1

数据:

Date          Stock    Peak    Trough    Price
2002-01-01    33.78    False   False     25
2002-01-02    34.19    False   False     35
2002-01-03    35.44    False   False     33
2002-01-04    36.75    False   False     38

[当股票价格高于或等于从第4列开始的行中的最大值时,我使用此行代码将每行的'Peak'设置为true:

df['Peak'] = np.where(df.iloc[:,4:].max(axis=1) >= df[stock], 'False', 'True')

但是,我正在努力做到这一点,以使前X行和后Y行不受影响。假设在此示例中X和Y均为10。我这样修改它:

df.iloc[10:-10]['Peak'] = np.where(df.iloc[10:-10,4:].max(axis=1) >= df.iloc[10:-10][stock], 'False', 'True')

这给我一个错误SettingWithCopyWarning,也不再起作用。有谁知道如何获得所需的结果,以使前X行和后Y行始终为False?]

python-3.x pandas numpy
1个回答
2
投票

我相信在使用get_loc进行分配时,您需要get_loc来指定列索引:

df.iloc[]

尝试这里是一个测试用例:

df.iloc[10:,df.columns.get_loc('year')] = (np.where(df.iloc[10:,4:].max(axis=1)
                           >= df.iloc[10:,df.columns.get_loc('stock')],'False', 'True'))

尝试将索引2中的列D设置为np.random.seed(123) df = pd.DataFrame(np.random.randint(0,100,(5,4)),columns=list('ABCD')) print(df) A B C D 0 66 92 98 17 1 83 57 86 97 2 96 47 73 32 3 46 96 25 83 4 78 36 96 80 ,我们得到相同的错误:

np.nan

试图从DataFrame的切片副本上设置一个值。尝试使用.loc [row_indexer,col_indexer] =值

请参见文档中的注意事项:df.iloc[2:]['D']=np.nan “”“启动IPython内核的入口点。

使用http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy成功)尝试同样的方法来避免chained assignment

get_loc
© www.soinside.com 2019 - 2024. All rights reserved.