I have a sample dataframe df and an arraynas 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
You should be able to do
out = df[df.index.isin(n)]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With