【问题标题】:Combining iloc and loc结合 iloc 和 loc
【发布时间】:2019-03-30 20:39:15
【问题描述】:

我正在尝试将 iloc 和 loc 结合起来,有可能吗?

我特别想:

  • 为行值以 (:train_size) 的形式给出整数

  • 给出列值的列名列表(替换下面代码中的 [0,1])

    training_set = dataset.iloc[:train_size,[0,1]].values

尝试

training_set = dataset.loc[:train_size,[list_input_and_y_parameters]].values

给出错误信息

TypeError: cannot do slice indexing on with these indexers [4275] of

有没有办法做到这一点?

非常感谢

【问题讨论】:

  • 我相信我们需要更多信息才能清楚地断言这一点。比如我们需要知道你dataset长什么样子,列和索引是什么?

标签: python pandas


【解决方案1】:

您可以链接此操作或仅使用ilocIndex.get_indexer 作为列表中列的位置:

training_set = dataset.iloc[:train_size].loc[:, ['col1','col2']].values

training_set = dataset.iloc[:train_size, df.columns.get_indexer(['col1','col2'])].values

【讨论】:

  • 我认为使用Index.get_indexer 是最好的选择,因为它也适用于分配
  • 您知道在第一个示例中使用链式索引是否合适?该文档不鼓励链式索引,例如 dfmi['one']['second'],但它不包括链式 loc。 pandas.pydata.org/pandas-docs/stable/user_guide/…
【解决方案2】:

由于链接lociloc 可能导致SettingWithCopyWarning,因此不需要使用Index.get_indexer 的选项可能是(假设索引中没有重复项): p>

training_set = dataset.loc[dataset.index[:train_size], ['col1','col2']].values

【讨论】:

    猜你喜欢
    • 2018-02-08
    • 2021-12-06
    • 2015-10-14
    • 2019-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多