gpt4 book ai didi

python - 设置单个值时如何避免SettingWithCopyWarning?

转载 作者:行者123 更新时间:2023-12-01 08:36:00 24 4
gpt4 key购买 nike

在这种情况下如何避免警告SettingWithCopyWarning

通常,使用先前创建的 DataFrame 的 copy() 就足够了。在这种情况下这是没有意义的:

import pandas as pd
import numpy as np
df = pd.DataFrame({"a": [7, 2, 3], "b": [4, 5, 6], "c": [np.nan, np.nan, np.NaN]})
df.c.iloc[0] = 100

.

SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
self._setitem_with_indexer(indexer, value)

最佳答案

使用默认 RangeIndex 时的解决方案 DataFrame.loc指定索引和列值:

df.loc[0, 'c'] = 100
print (df)
a b c
0 7 4 100.0
1 2 5 NaN
2 3 6 NaN

如果想按DataFrame.iloc的位置设置有必要Index.get_loc对于列 c 的位置:

df.iloc[0, df.columns.get_loc('c')] = 100

关于python - 设置单个值时如何避免SettingWithCopyWarning?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53721161/

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