大熊猫中的loc函数

ken*_*way 17 python machine-learning pandas

任何人都可以解释为什么loc在python pandas中使用的例子如下所示?

for i in range(0, 2):
  for j in range(0, 3):
    df.loc[(df.Age.isnull()) & (df.Gender == i) & (df.Pclass == j+1),
            'AgeFill'] = median_ages[i,j]
Run Code Online (Sandbox Code Playgroud)

Kir*_*ane 21

.loc这里推荐使用因为方法df.Age.isnull(),df.Gender == i并且df.Pclass == j+1可能返回数据帧的切片视图或者可能返回副本.这可能会混淆熊猫.

如果你不使用.loc你最终会串联调用所有3个条件,这会引发一个称为链式索引的问题..loc但是,当您使用时,您只需一步即可访问所有条件,并且不再混淆熊猫.

您可以阅读有关此内容的更多信息以及一些不使用时.loc会导致操作在pandas文档中失败的示例.

简单的答案是,虽然你可以经常逃避不使用.loc和简单地打字(例如)

df['Age_fill'][(df.Age.isnull()) & (df.Gender == i) & (df.Pclass == j+1)] \
                                                          = median_ages[i,j]
Run Code Online (Sandbox Code Playgroud)

你总会得到SettingWithCopy警告,你的代码会有点麻烦.

根据我的经验.loc,我花了一段时间来解决问题,更新我的代码有点烦人.但它真的非常简单而且非常直观:df.loc[row_index,col_indexer].

有关更多信息,请参阅有关索引和选择数据的pandas文档.