3

I have an array with numbers which corresponds to the row numbers that need to be selected from a DataFrame. For example, arr = np.array([0,0,1,1]) and the DataFrame is seen below. arr is the row number and not the index.

Index   A   B   C   D
3      10   0   0   0
4      5    2   0   0

Using arr I would like to produce a DataFrame that looks like this

  Index    A    B   C   D
    3      10   0   0   0
    3      10   0   0   0
    4      5    2   0   0
    4      5    2   0   0

1 Answer 1

8

You can use iloc with integer indexing:

df.iloc[[0,0,1,1], :]   # or df.iloc[arr, :]

#    A  B   C   D
#Index              
#3  10  0   0   0
#3  10  0   0   0
#4   5  2   0   0
#4   5  2   0   0
Sign up to request clarification or add additional context in comments.

1 Comment

Nice. I think df.iloc[arr] also works in this case.

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.