通过数组过滤DataFrame索引

时间:2018-07-16 18:49:22

标签: python arrays pandas dataframe indexing

我有一个示例数据帧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

array([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

2 个答案:

答案 0 :(得分:2)

您应该能够做到

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

答案 1 :(得分:1)

您的解决方案无效,因为您正在尝试比较短数组n和df.index的相等值。您可以使用pandas fancy-indexing来获取解决方案。如果nnp.array,则下面的命令会正常工作。

df.loc[n]