Search code examples
pandasdataframereindex

how to create a time series column and reindex in pandas?


How to create a column and reindex in pandas?

I'm a new pandas learner. I have 5 rows dataframe as follow:

   A     B     C     D
0  2.34  3.16  99.0  3.2
1  2.1   55.5  77.5  1
2  22.1  54    89    33
3  23    1.24  4.7   5
4  45    2.5   8.7   99

I want to replace index column 0,1...4 with new index 1 to 5. My expected output is:

   A     B     C     D
1  2.34  3.16  99.0  3.2
2  2.1   55.5  77.5  1
3  22.1  54    89    33
4  23    1.24  4.7   5
5  45    2.5   8.7   99

What I did is I create a new column:

new_index = pd.DataFrame({'#': range(1, 5 + 1 ,1)})

Then I tried to reindex:

df.reindex(new_index)

But I got error: ValueError: Buffer has wrong number of dimensions (expected 1, got 2)

What should I do to reindex the former index? Thanks.


Solution

  • Use set_index

    In [5081]: df.set_index([range(1, 6)])
    Out[5081]:
           A      B     C     D
    1   2.34   3.16  99.0   3.2
    2   2.10  55.50  77.5   1.0
    3  22.10  54.00  89.0  33.0
    4  23.00   1.24   4.7   5.0
    5  45.00   2.50   8.7  99.0
    

    Or set values of df.index

    In [5082]: df.index = range(1, 6)
    
    In [5083]: df
    Out[5083]:
           A      B     C     D
    1   2.34   3.16  99.0   3.2
    2   2.10  55.50  77.5   1.0
    3  22.10  54.00  89.0  33.0
    4  23.00   1.24   4.7   5.0
    5  45.00   2.50   8.7  99.0
    

    Details

    Original df

    In [5085]: df
    Out[5085]:
           A      B     C     D
    0   2.34   3.16  99.0   3.2
    1   2.10  55.50  77.5   1.0
    2  22.10  54.00  89.0  33.0
    3  23.00   1.24   4.7   5.0
    4  45.00   2.50   8.7  99.0