【问题标题】:loc function in pandas大熊猫中的 loc 函数
【发布时间】:2015-10-12 19:20:15
【问题描述】:

谁能解释一下为什么在 python pandas 中使用 loc 并举例如下所示?

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]

【问题讨论】:

  • 在您的示例中,使用.loc 主要是因为您尝试通过列索引AgeFill 访问单元格。

标签: python pandas machine-learning


【解决方案1】:

这里推荐使用.loc,因为df.Age.isnull()df.Gender == idf.Pclass == j+1 方法可能会返回数据框切片的视图或可能返回副本。这会让 pandas 感到困惑。

如果您不使用.loc,您最终会串联调用所有 3 个条件,这会导致您遇到一个称为链式索引的问题。但是,当您使用.loc 时,您可以一步访问所有条件,pandas 不再感到困惑。

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

简单的答案是,虽然您通常可以不使用 .loc 而只是输入(例如)

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

您总是会收到SettingWithCopy 警告,并且您的代码会因此变得有些混乱。

根据我的经验,.loc 花了我一段时间才弄清楚,更新我的代码有点烦人。但它真的超级简单而且非常直观:df.loc[row_index,col_indexer]

有关更多信息,请参阅Indexing and Selecting Data 上的 pandas 文档。

【讨论】:

    猜你喜欢
    • 2020-07-09
    • 2021-02-07
    • 2016-09-10
    • 2021-12-06
    • 2016-07-03
    • 2018-10-21
    • 2018-11-24
    • 2020-08-20
    • 2018-09-11
    相关资源
    最近更新 更多