数据:
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?
最佳答案
我相信您需要一个 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'))
这里有一个测试用例:
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
尝试将索引 2 中的 D 列设置为 np.nan
我们得到相同的错误:
df.iloc[2:]['D']=np.nan
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/user_guide/indexing.html#returning-a-view-versus-a-copy """Entry point for launching an IPython kernel.
尝试同样避免 chained assignment使用get_loc
(成功)
df.iloc[2:,df.columns.get_loc('D')] = np.nan
print(df)
A B C D
0 66 92 98 17.0
1 83 57 86 97.0
2 96 47 73 NaN
3 46 96 25 NaN
4 78 36 96 NaN
关于python-3.x - python : SettingWithCopyWarning when trying to set value to True based on condition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60704651/