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.
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.
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])
drop here is a really nice solution. I already upvoted your first answer, but I think this edit is even better.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.