【问题标题】:Filtering DataFrame Index through Array通过数组过滤 DataFrame 索引
【发布时间】:2018-12-24 09:17:09
【问题描述】:

我有一个示例数据框df 和一个数组n,如下所示。我想根据索引中的数组值进行过滤。输出数据框也如下所示。我试过Out = df[df.index == n]Out = df.loc[df.index == n ] 都没有工作,给出错误Lengths must match to compare。谁能帮我解决这个问题。

df = Date Open High Low Close Adj Close Volume 0 2007-06-18 0.33979 0.33979 0.33979 0.33979 0.33979 1591888 1 2007-06-29 0.33074 0.33074 0.33074 0.33074 0.33074 88440 2 2007-06-20 0.33526 0.33526 0.33526 0.33526 0.33526 3538 3 2007-06-21 0.32113 0.32113 0.32113 0.32113 0.32113 3550 4 2007-06-22 0.34713 0.34713 0.34713 0.34713 0.34713 670 6 2007-06-18 0.33979 0.33979 0.33979 0.33979 0.33979 1591888 7 2007-06-29 0.33074 0.33074 0.33074 0.33074 0.33074 88440 8 2007-06-20 0.33526 0.33526 0.33526 0.33526 0.33526 3538 9 2007-06-21 0.32113 0.32113 0.32113 0.32113 0.32113 3550 10 2007-06-22 0.34713 0.34713 0.34713 0.34713 0.34713 670

数组([ 0, 1, 2, 3])

输出 = Date Open High Low Close Adj Close Volume 0 2007-06-18 0.33979 0.33979 0.33979 0.33979 0.33979 1591888 1 2007-06-29 0.33074 0.33074 0.33074 0.33074 0.33074 88440 2 2007-06-20 0.33526 0.33526 0.33526 0.33526 0.33526 3538 3 2007-06-21 0.32113 0.32113 0.32113 0.32113 0.32113 3550

【问题讨论】:

    标签: python arrays pandas dataframe indexing


    【解决方案1】:

    你应该可以的

    out = df[df.index.isin(n)]
    

    【讨论】:

    • 如果有 DateTime Index 并且我的数组如上所示。反正有没有根据数组的行数过滤它? .这里的数组编号是行号
    • 当然 - 如果索引是日期时间而不是整数,您可以使用 df.loc[n]
    • 谢谢!但这给了我unhashable type: 'numpy.ndarray' 错误
    【解决方案2】:

    您的解决方案不起作用,因为您试图比较短数组 n 和 df.index 的相等值。您可以使用pandas fancy-indexing 来获取您的解决方案。如果nnp.array,以下将正常工作。

    df.loc[n]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-12
      • 2019-03-17
      • 2017-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多