首頁  >  文章  >  後端開發  >  為什麼在 .loc 索引中仍有SettingWithCopyWarning?

為什麼在 .loc 索引中仍有SettingWithCopyWarning?

DDD
DDD原創
2024-10-28 08:03:02784瀏覽

Why Does the SettingWithCopyWarning Persist with .loc Indexing?

SettingWithCopyWarning 持續使用.loc 索引

當使用.loc[row_indexer,col_indexer] = value 進行資料操作時,您仍可能會遇到設定WithCopyWarning。這通常是由於在應用更改之前複製基礎資料幀引起的。

逐步錯誤重現

考慮以下資料幀df:

<code class="python">import pandas as pd

d = {'col1': [1, 2, 3, 4], 'col2': [3, 4, 5, 6]}
df = pd.DataFrame(data=d)</code>

最初,使用.loc 修改列不會觸發任何警告:

<code class="python">df['new_column'] = None
df.loc[0, 'new_column'] = 100</code>

但是,如果過濾df 以建立新的資料框new_df,則使用.loc 進行後續修改可能會導致警告:

<code class="python">new_df = df.loc[df.col1 > 2]
new_df.loc[2, 'new_column'] = 100</code>

發生這種情況是因為new_df是df 的視圖或切片,且應用於new_df 的變更不會傳播回df。

解決方案

要消除警告,需要在應用過濾器之前複製df:

<code class="python">new_df_copy = df.loc[df.col1 > 2].copy()
new_df_copy.loc[2, 'new_column'] = 100</code>

透過使用.copy(),創建一個獨立於df 的新資料幀,允許更改到new_df_copy而不修改df。

避免convert_objects

也可以透過convert_objects函式觸發SettingWithCopyWarning。為了避免這種情況,請在呼叫convert_objects之前使用.astype(str):

<code class="python">value1['Total Population'] = value1['Total Population'].astype(str).convert_objects(convert_numeric=True)</code>

以上是為什麼在 .loc 索引中仍有SettingWithCopyWarning?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn