Pandas 赋值中的df.loc[rows,[col]]与df.loc[rows,col]

Pandas 赋值中的df.loc[rows,[col]]与df.loc[rows,col],pandas,Pandas,以下作业有什么不同的表现 df.loc[rows, [col]] = ... df.loc[rows, col] = ... 例如: r = pd.DataFrame({"response": [1,1,1],},index = [1,2,3] ) df = pd.DataFrame({"x": [999,99,9],}, index = [3,4,5] ) df = pd.merge(df, r, how="left", left_index=True, right_index=True)

以下作业有什么不同的表现

df.loc[rows, [col]] = ...
df.loc[rows, col] = ...
例如:

r = pd.DataFrame({"response": [1,1,1],},index = [1,2,3] )
df = pd.DataFrame({"x": [999,99,9],}, index = [3,4,5] )
df = pd.merge(df, r, how="left", left_index=True, right_index=True)

df.loc[df["response"].isnull(), "response"] = 0
print df
     x  response
3  999       0.0
4   99       0.0
5    9       0.0
但是

为什么我要期望第一个和第二个表现不同

df.loc[df["response"].isnull(), ["response"]]
返回一个数据帧,因此,如果要为其分配某些内容,则必须通过索引和列对齐

演示:

或者,您可以指定形状相同的数组/矩阵:

In [83]: df.loc[df["response"].isnull(), ["response"]] = [11, 12]

In [84]: df
Out[84]:
     x  response
3  999       1.0
4   99      11.0
5    9      12.0

我也会考虑使用<代码> fILNA()<代码>方法:

In [88]: df.response = df.response.fillna(0)

In [89]: df
Out[89]:
     x  response
3  999       1.0
4   99       0.0
5    9       0.0
df.loc[df[“response”].isnull(),“response”]不也会返回一个数据帧吗?啊——它确实是这样。
In [83]: df.loc[df["response"].isnull(), ["response"]] = [11, 12]

In [84]: df
Out[84]:
     x  response
3  999       1.0
4   99      11.0
5    9      12.0
In [88]: df.response = df.response.fillna(0)

In [89]: df
Out[89]:
     x  response
3  999       1.0
4   99       0.0
5    9       0.0