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