JavaBeginner JavaBeginner - 2 months ago 12
Python Question

Get rows from DataFrame based on array of indices

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

Answer

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