25

I have a series data type which was generated by subtracting two columns from pandas data frame.

I want to remove the first element from the series which would be x[-1] in R. I can get it to work in np array class but series class doesn't work.

3
  • Does x.idx[-1,] do what you want? Commented Jan 6, 2016 at 19:36
  • It says 'Series' object has no attribute 'idx' Commented Jan 6, 2016 at 19:46
  • I'm sorry, I meant iloc, not idx. Commented Jan 6, 2016 at 20:59

2 Answers 2

46

Using integer based slicing should work - (see docs):

s.iloc[1:]

If you prefer to drop rather than slice, you could use the built-in drop method:

s.drop(s.index[0])

To remove several items, you would include a list of index positions:

s.drop(s.index[[0, 2, 4]])

or a slice:

s.drop(s.index[1: 4])
Sign up to request clarification or add additional context in comments.

1 Comment

Using drop here is a really nice solution. I already upvoted your first answer, but I think this edit is even better.
2

Python doesn't have a way of slicing out a position the way that R does. If you only need to remove the first or last element, the previous posted solution: s.iloc[1:] is probably the best. If you need to remove multiple elements, or an element in the middle of your series you can do so with the following:

In [29]: x = pd.Series(np.random.randn(10))

In [34]: x[~x.index.isin([0, 3, 4])]
Out[34]: 1    0.884089
         2    0.921271
         5   -0.847967
         6   -0.088892
         7   -0.765241
         8   -0.084489
         9   -0.581152
         dtype: float64

In this case we removed the 0, 3 and 4 positions.

This is a bit messier, so like I said the previous solution may be the best for what you need, however this does have some additional functionality.

It's worth noting that this solution will only work if your index is numeric and consecutive starting with 0.

1 Comment

There's x.drop(x.index[[0, 3, 4]]).

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.