想象我有一个数据框,我希望根据现有值在框架中的位置更改现有值(例如
iloc
):
(Pdb) df = pd.DataFrame([["a", 1], ["b", 2], ["c", 3]], columns=["let", "num"])
(Pdb) df
let num
0 a 1
1 b 2
2 c 3
在
pandas
中使用写时复制的正确方法是什么?
(Pdb) df["num"].iloc[1:] = 22
<stdin>:1: FutureWarning: ChainedAssignmentError: behaviour will change in pandas 3.0!
You are setting values through chained assignment. Currently this works in certain cases, but when using Copy-on-Write (which will become the default behaviour in pandas 3.0) this will never work to update the original DataFrame or Series, because the intermediate object on which we are setting values will behave as a copy.
A typical example is when you are setting values in a column of a DataFrame, like:
df["col"][row_indexer] = value
Use `df.loc[row_indexer, "col"] = values` instead, to perform the assignment in a single step and ensure this keeps updating the original `df`.
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
(Pdb) df
let num
0 a 1
1 b 22
2 c 22
我今天可以做到,但有一个不祥的警告!
谢谢, /YGA
根据 ouroborus1 的评论:
df.iloc[1:, df.columns.get_loc('num')] = 22