Removing elements from pandas series in python

jay2020 picture jay2020 · Jan 6, 2016 · Viewed 38.6k times · Source

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.

Answer

Stefan picture Stefan · Jan 6, 2016

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])