gpt4 book ai didi

python - Pandas SettingWithCopyWarning

转载 作者:IT老高 更新时间:2023-10-28 20:31:37 26 4
gpt4 key购买 nike

Python 3.4 和 Pandas 0.15.0

df 是一个数据框,而 col1 是一个列。使用下面的代码,我正在检查值 10 的存在并将这些值替换为 1000。

df.col1[df.col1 == 10] = 1000

这是另一个例子。这一次,我根据索引更改 col2 中的值。

df.col2[df.index == 151] = 500

这两个都会产生以下警告:

-c:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

最后,

cols = ['col1', 'col2', 'col3']
df[cols] = df[cols].applymap(some_function)

这会产生类似的警告,并添加一个建议:

Try using .loc[row_indexer,col_indexer] = value instead

我不确定我是否理解警告中指出的讨论。写这三行代码有什么更好的方法?

请注意,这些操作有效。

最佳答案

这里的问题是:df.col1[df.col1 == 10] 返回一个副本。

所以我会说:

row_index = df.col1 == 10
# then with the form .loc[row_indexer,col_indexer]
df.loc[row_index, 'col1'] = 100

关于python - Pandas SettingWithCopyWarning,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26724378/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com