【问题标题】:Select rows by indices - Pandas loc - any missing labels按索引选择行 - Pandas loc - 任何缺失的标签
【发布时间】:2021-01-26 14:36:56
【问题描述】:

Python 3.8.5 版/Pandas 1.1.2 版

为了显示从 0 到 99 的索引行,我使用了

df[df.col_1 > 60].loc[range(0,99), 'col_2']

但是我收到了这个错误信息

KeyError:“将列表喜欢传递给带有任何缺失标签的 .loc 或 [] 不再支持。缺少以下标签: Int64Index([ 1, 3, 4, 6, 7,\n ...\n 95, 96, 97, 98, 99],\n dtype='int64',长度=72)。看 https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#deprecate-loc-reindex-listlike"

作为替代方案,我有这个适用于我的情况的选项:

df[df.col_1 > 2].loc[0:4, 'col_2']

我听说新版 pandas 不再接受它。 感谢您的任何确认。

【问题讨论】:

    标签: python pandas indexing label pandas-loc


    【解决方案1】:

    试试下面的方法。

    这里我们不考虑range(99)的所有值,而是取交集。

    df[df.col_1 > 60].loc[df[df.col_1 > 60].index.intersection(range(99)), 'col_2']
    

    【讨论】:

      【解决方案2】:

      由于过滤器 df.col1>60 一些索引不存在于数据帧中,但你在 loc 中给出了 range(0,99) 的参数,因此它们不存在,因此引发了错误。如果你想要 100 个元素。 用这个

      df[df.col_1 > 60].iloc[range(0,99), 'col_2']
      

      如果你想在第 100 个元素中试试这个:

      df=df.loc[range(99), ["col_1",'col_2']]
      df[df[loc_1]>60].drop("col_1",axis=1)
      

      【讨论】:

        【解决方案3】:

        我认为& 最好将 2 个掩码链并传递给一个 loc

        df[(df.col_1 > 60) & df.index.isin(range(99)), 'col_2']
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-10-10
          • 1970-01-01
          • 1970-01-01
          • 2019-04-17
          • 1970-01-01
          • 2019-03-03
          • 2018-06-01
          相关资源
          最近更新 更多