Search code examples
pythonpandassimulationmontecarlo

Reset Series index without turning into DataFrame


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.


Solution

  • 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.