在赋值中,df.loc[rows, [col]]与df.loc[rows, col]有什么区别?

3
以下任务有何不同之处?
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"]] = 0
print df
     x  response
3  999       1.0
4   99       0.0
5    9       0.0

为什么我要期望第一个行为不同于第二个?
1个回答

4
df.loc[df["response"].isnull(), ["response"]]

返回一个DataFrame,所以如果您想将某些内容分配给它,则必须按照索引和列进行对齐。

演示:

In [79]: df.loc[df["response"].isnull(), ["response"]] = \
             pd.DataFrame([11,12], columns=['response'], index=[4,5])

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

或者你可以分配一个相同形状的数组/矩阵:

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

我建议使用 fillna() 方法:

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"] 也会返回一个数据框吗? - user48956
啊 -- 原来是这样。 - user48956

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接