SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
时间: 2023-10-14 13:21:34 浏览: 109
This warning is raised when you try to modify a subset of a DataFrame obtained using indexing or slicing. When you use indexing or slicing to obtain a subset of a DataFrame, pandas returns a view of the original DataFrame rather than a new copy. If you try to modify this subset, pandas may not be able to determine whether you want to modify the original DataFrame or just the subset, which can lead to unexpected behavior.
To avoid this warning, you should use the `.loc` or `.iloc` accessor to modify the original DataFrame directly:
```
df.loc[indexer, column] = new_value
```
Alternatively, you can make a copy of the subset and modify the copy instead:
```
subset = df.loc[indexer, column].copy()
subset[column] = new_value
df.loc[indexer, column] = subset
```
By making a copy of the subset and modifying the copy, you avoid modifying the original DataFrame accidentally.
阅读全文