Python 将值设置为数据帧:警告试图在数据帧的切片副本上设置值
为什么会这样? 我将用熊猫制作4个数据帧:Python 将值设置为数据帧:警告试图在数据帧的切片副本上设置值,python,pandas,warnings,Python,Pandas,Warnings,为什么会这样? 我将用熊猫制作4个数据帧: >>> df = pd.DataFrame({"A": ["One","Two","Three"], "B": ["Two","Three","Four"], "C": ["Three","Four","Five"], "D": ["Four","Five","Six"]}) >>> df A B C D 0 One Two Three Four 1 T
>>> df = pd.DataFrame({"A": ["One","Two","Three"], "B": ["Two","Three","Four"], "C": ["Three","Four","Five"], "D": ["Four","Five","Six"]})
>>> df
A B C D
0 One Two Three Four
1 Two Three Four Five
2 Three Four Five Six
>>> df["C"][1] = "One Hundred"
一切顺利;现在让我们先做两列,然后添加两列,一列带“”,另一列带NaN
>>> df = pd.DataFrame({"A": [1,2,3], "B": [2,3,4]})
>>> df
A B
0 1 2
1 2 3
2 3 4
>>> df["C"] = ""
>>> df["D"] = pd.np.nan
>>> df
A B C D
0 1 2 NaN
1 2 3 NaN
2 3 4 NaN
>>> df["C"][1] = "hello"
Warning (from warnings module):
File "__main__", line 1
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
一个警告出现了!
好的:(这就是问题:这个警告是为了什么?)
但让我们继续:
现在我这样做:
>>> df = pd.DataFrame({"A": [1,2,3], "B": [2,3,4], "C": [3,4,5], "D": [4,5,6]})
>>> df
A B C D
0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
>>> df["C"][1] = 100
并且没有出现任何警告。嗯
现在让我们再次触发警告:
>>> df = pd.DataFrame({"A": [1,2,3], "B": [2,3,4]})
>>> df["C"] = ""
>>> df["D"] = pd.np.nan
>>> df
A B C D
0 1 2 NaN
1 2 3 NaN
2 3 4 NaN
>>> df["C"][1] = "hello"
>>>
这次没有警告
我正在使用IDLE 3.5.2,Python版本:3.5.2
这是虫子吗?我不知道,因为我在学习
我是否应该用所有列编写一个新的单独数据帧,然后每次都将其与df的列相等
我应该做一个python列表吗
有没有一种方法可以在没有警告的情况下遍历和编辑原始数据帧
为什么不是每次都会出现这样的警告
谢谢您的时间。正确的方法是:
df["column_name"][0] = "hello"
如果使用点列名称的方式,则显然是在选择切片。如果您使用这种(正确的)方法,可以说您是在“触摸单元格”。您可以使用
loc
或iloc
df
Out[1445]:
A A_1 B
0 1.0 1.0 A
1 NaN NaN A
2 3.0 3.0 NaN
3 4.0 4.0 B
df.iloc[1,1]='Yourvalue1'
df
Out[1447]:
A A_1 B
0 1.0 1 A
1 NaN Yourvalue1 A
2 3.0 3 NaN
3 4.0 4 B
df.loc[1,'A']
Out[1448]: nan
df.loc[1,'A']='Yourvalue2'
df
Out[1450]:
A A_1 B
0 1 1 A
1 Yourvalue2 Yourvalue1 A
2 3 3 NaN
3 4 4 B
我认为正确的方法是编写一个函数并与apply方法一起使用
df.apply(my_function, axis=1)
如图所示,熊猫可以超快速完成任务。这不是正确的方法,因为警告消息中的文档提供了链接。@Phillv,
pandas
不会提升链式表达式。在这种情况下,文档更倾向于使用df.loc
或df.iloc
。这给了我完全相同的警告消息。