Reset Series index without turning into DataFrame
Asked Answered
R

1

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.

Runge answered 13/3, 2018 at 20:58 Comment(0)
P
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.

Pelagia answered 13/3, 2018 at 21:2 Comment(2)
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)Runge
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.Pelagia

© 2022 - 2024 — McMap. All rights reserved.