【发布时间】:2021-06-08 02:24:24
【问题描述】:
这是我的 df:
In[12]: df = pd.DataFrame(data = list("aabbcc"), columns = ["s"], index=range(11,17))
In[13]: df
Out[13]:
s
11 a
12 a
13 b
14 b
15 c
16 c
让我们尝试根据索引替换值:
In[14]: df.loc[11, "s"] = 'A'
In[15]: df
Out[15]:
s
11 A
12 a
13 b
14 b
15 c
16 c
In[16]: df.ix[12, "s"] = 'B'
In[17]: df
Out[17]:
s
11 A
12 B
13 b
14 b
15 c
16 c
有效!但是如果我根据位置而不是索引做同样的事情,说这样的话,但它显示 ValueError (ValueError: Can only index by location with a [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array]):
In[18]: df.iloc[1, "s"] = 'b'
而且,如果我尝试这样的事情:
df.s.iloc[1] = "b"
我收到此警告:
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
【问题讨论】:
-
您遇到的第一个错误是因为您尝试对字符串使用基于整数的索引。试试
df.iloc[1, 0] = 'b'。这是您正在运行的完整代码吗?df.s.iloc[1] = "b"在我运行它时不会产生错误。如果df是通过切片另一个数据框创建的,我希望看到您收到的警告。