比方說,我有以下的熊貓數據框:大熊貓:操作使用GROUPBY產量SettingWithCopyWarning
df = pd.DataFrame({
'team': ['Warriors', 'Warriors', 'Warriors', 'Rockets', 'Rockets'],
'player': ['Stephen Curry', 'Klay Thompson', 'Kevin Durant', 'Chris Paul', 'James Harden']})
當我嘗試組對team
列和執行操作,我得到一個SettingWithCopyWarning
:
for team, team_df in df.groupby(by='team'):
# team_df = team_df.copy() # produces no warning
team_df['rank'] = 10 # produces warning
team_df.loc[:, 'rank'] = 10 # produces warning
SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
df_team['rank'] = 10
如果我取消註釋生成子DataFrame副本的行,我不會收到錯誤。這是避免這種警告的最佳做法嗎?或者我做錯了什麼?
注意我不想編輯原始DataFrame df
。另外我知道這個例子可以做得更好,但我的用例更復雜,需要對原始DataFrame進行分組,並根據不同的DataFrame和該唯一組的規格執行一系列操作。
偉大的鏈接到文章! – piRSquared
@piRSquared:我從[Alexander](https://stackoverflow.com/users/2411802/alexander),[這裏]瞭解了[文章](https://www.dataquest.io/blog/settingwithcopywarning/) (https://stackoverflow.com/questions/38809796/pandas-still-getting-settingwithcopywarning-even-after-using-loc/38810015#comment76884959_38809796)。 – unutbu