Search code examples
pandasdataframereindex

Manipulating indices in a pandas dataframe


The problem: I want to shift the index by adding 2 (index+=2) to match it with the indices of a .csv file.

I have a dataframe which looks as follows:

Counts Counts
7 10951.0 870.0
8 8653.0 1772.0
19 28598.0 37608.0
20 115266.0 123491.0
21 73097.0 145261.0

my desired result would look like this:

Counts Counts
9 10951.0 870.0
10 8653.0 1772.0
21 28598.0 37608.0
22 115266.0 123491.0
23 73097.0 145261.0

Thanks for the help and sorry if there is anything wrong with my question.

This function:

shifted_df.index = pd.Index(range(2, len(shifted_df) + 2))

is the first one which as actually changing the index of my dataframe but it just overwrites the given index with the numbers 2 to len(shifted_df)


Solution

  • If you want to modify your shifted_df DataFrame in place:

    shifted_df.index += 2
    

    If you want to create a new DataFrame, and assuming df the original DataFrame use set_axis:

    shifted_df = df.set_axis(df.index+2)
    

    Or rename:

    shifted_df = df.rename(lambda x: x+2)
    

    Output:

              col1      col2
    9      10951.0     870.0
    10      8653.0    1772.0
    21     28598.0   37608.0
    22    115266.0  123491.0
    25      1599.0    4536.0
    27     61142.0   46921.0
    ...
    1302  117695.0  108044.0