5

When I use Series.reset_index() my variable turns into a DataFrame object. Is there any way to reset the index of a series without incurring this result?

The context is a simulation of random choices based on probability (monte carlo sim), where selections made from series are omitted with series.pop(item).

I require the index reset because I iterate through in order to create a cumulative frequency series.

Drise
  • 4,310
  • 5
  • 41
  • 66
randyslavage
  • 65
  • 1
  • 5

1 Answers1

6

You can try drop=True in .reset_index i.e. series.reset_index(drop=True, inplace=True)

According to document:

drop : boolean, default False

Do not try to insert index into dataframe columns.

Example:

series = pd.Series([1,2,3,4,5,1,1])
print(series)

Series result:

0    1
1    2
2    3
3    4
4    5
5    1
6    1
dtype: int64

selecting some values from series:

filtered = series[series.values==1]
print(filtered)

Result:

0    1
5    1
6    1
dtype: int64

Reseting index:

filtered.reset_index(drop=True, inplace=True)
print(filtered)

Result:

0    1
1    1
2    1
dtype: int64

With type(filtered) still returns Series.

Community
  • 1
  • 1
niraj
  • 17,498
  • 4
  • 33
  • 48
  • however this seems to empty the series, if reassigning a reset-indexed `series` to itself i.e. `f = f.reset_index(drop=True, inplace=True)` – randyslavage Mar 15 '18 at 18:26
  • 1
    You do not need to reassign it after `inplace`, it does not return anything, it already changed the original series `f`. If you really need to assign to something else then remove `inplace=True`. – niraj Mar 15 '18 at 18:29