Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Set a column value to be the index label of a dataframe

I have a dataframe that looks like this:

date rate

0 2015-12-11 0.253330

1 2015-12-12 NaN

2 2015-12-13 NaN

3 2015-12-14 0.210000

4 2015-12-15 0.220000

5 2015-12-16 0.220000

6 2015-12-17 0.365000

7 2015-12-18 0.450000

How would I change the index of the dataframe so that it labeled as the date column i.e.

rate

2015-12-11 0.253330

2015-12-12 NaN

2015-12-13 NaN

2015-12-14 0.210000

2015-12-15 0.220000

2015-12-16 0.220000

2015-12-17 0.365000

2015-12-18 0.450000

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use the set_index() method of the pandas dataframe to change the index of the dataframe. Here’s the code to do it:

import pandas as pd

# create the dataframe
data = {'date': ['2015-12-11', '2015-12-12', '2015-12-13', '2015-12-14',
                 '2015-12-15', '2015-12-16', '2015-12-17', '2015-12-18'],
        'rate': [0.25333, None, None, 0.21, 0.22, 0.22, 0.365, 0.45]}

df = pd.DataFrame(data)

# change the index of the dataframe
df = df.set_index('date')

df then looks like this:

               rate
date               
2015-12-11  0.25333
2015-12-12      NaN
2015-12-13      NaN
2015-12-14  0.21000
2015-12-15  0.22000
2015-12-16  0.22000
2015-12-17  0.36500
2015-12-18  0.45000
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading