3

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

2 Answers 2

4

You should be able to do

out = df[df.index.isin(n)]
Sign up to request clarification or add additional context in comments.

3 Comments

what if there is DateTime Index and my array is as shown above. Is there anyway to filter it on the basis of row number of array ? . Here the array number are row numbers
Sure - if the index is a datetime rather than integers, you can just use df.loc[n] .
Thanks! but that is giving me the unhashable type: 'numpy.ndarray' error
1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.