Reputation: 165
I have a sample dataframe df
and an arrayn
as shown below. I want to filter based on the array values which are in index. The output dataframe is shown below as well. I have tried Out = df[df.index == n]
and Out = df.loc[df.index == n ]
which is not working giving an error Lengths must match to compare
. Can anyone help me in solving this.
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])
Out =
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
Upvotes: 3
Views: 5925
Reputation: 7210
Your solutions do not work because you are trying to compare the equality value of your short array n
and df.index. You can use pandas fancy-indexing to get your solution. The following will work fine if n
is a np.array
.
df.loc[n]
Upvotes: 1