![](/img/trans.png)
[英]Pandas DataFrame: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
[英]Pandas, set on a copy of a slice from DataFrame problem
一段時間以來,我一直在為 Pandas 警告而苦苦掙扎。
我有一段非常簡單的代碼:
def get_delta(df):
df['delta_current_day'] = df['close'] - df['open']
df = df[pd.notnull(df['delta_current_day'])]
df['delta_next_day'] = df['delta_current_day'].shift(-1)
return df
每次我收到此錯誤時:
試圖在來自 DataFrame 的切片副本上設置值。 嘗試使用 .loc[row_indexer,col_indexer] = value 代替
我在stackoverflow上閱讀了很多關於它的問題,但沒有一個對我有用。 我試過這樣的事情:
df.loc[:, 'delta_next_day'] = df['delta_current_day'].shift(-1)
# OR
list = df['delta_current_day'].tolist()
df.loc[:, 'delta_next_day'] = list[:1]
但我仍然遇到同樣的錯誤。
我究竟做錯了什么?
我認為你需要DataFrame.copy
:
df = df[pd.notnull(df['delta_current_day'])].copy()
#df = df.loc[pd.notnull(df['delta_current_day'])] #or this
df['delta_next_day'] = df['delta_current_day'].shift(-1)
這是一個切片:
df = df[pd.notnull(df['delta_current_day'])]
A (
df['delta_current_day'].shift(-1)
) 值正試圖在一個 (df[pd.notnull(df['delta_current_day'])]
) 來自 DataFrame 的切片副本上設置
你也可以試試這個:
# Sample data.
df = pd.DataFrame({
'open': [100, 102, np.nan, 102],
'close': [101.5, 102.5, np.nan, 104]
})
def get_delta(df):
df = df.dropna().assign(delta_current_day=df.eval('close - open'))
return df.assign(delta_next_day=df['delta_current_day'].shift(-1))
>>> get_delta(df)
open close delta_current_day delta_next_day
0 100.0 101.5 1.5 0.5
1 102.0 102.5 0.5 2.0
3 102.0 104.0 2.0 NaN
當然,這會引入前瞻偏差。 為什么今天要使用明天的增量?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.