3

I have a numpy array as following:

    array([[1, 2],
           [3, 4],
           [5, 6],
           [7, 8]])

The array is called myArray, and I perform two indexing operations on the 2D array and get following results:

    In[1]: a1 = myArray[1:]
           a1

    Out[1]:array([[3, 4],
                 [5, 6],
                 [7, 8]])


    In[2]: a2 = myArray[:-1]
           a2

    Out[2]:array([[1, 2],
                  [3, 4],
                  [5, 6]])

Now, I have the same data in the form of a pandas df in two columns, let the data frame be df

      x    y
   0  1    2
   1  3    4
   3  5    6
   4  7    8

How to do the equivalent indexing/ slicing on two columns to get the same results as above for a1 and a2.

1
  • You can access the underlying numpy object using df.values. Commented May 8, 2017 at 3:29

1 Answer 1

1

Use iloc:

df.iloc[1:]

#   x   y
#1  3   4
#3  5   6
#4  7   8

df.iloc[:-1]

#   x   y
#0  1   2
#1  3   4
#3  5   6

Use head/tail:

df.head(-1)       # equivalent to df.iloc[:-1]

#   x   y
#0  1   2
#1  3   4
#3  5   6

df.tail(-1)       # equivalent to df.iloc[1:]

#   x   y
#1  3   4
#3  5   6
#4  7   8
Sign up to request clarification or add additional context in comments.

4 Comments

What if there are more columns in the df, and I just want to get the results on"x" and "y" columns. I know I can delete the columns after indexing, but is there a way to perform indexing on selected columns only?
How about df[['x', 'y']].iloc[1:]? Is this what you are looking for?
Thanks a lot, this is what I wanted.
@Psidom how to select multiple line which doesnt follow each other? e.g select lines from list=[1,10,25,100]

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.