在这种情况下,如何避免出现警告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)
答案 0 :(得分:1)
如果默认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
的位置来设置c
列的位置,则需要Index.get_loc
:
df.iloc[0, df.columns.get_loc('c')] = 100