pandas 将列值设置为数据框的索引标签[重复]

bcs8qyzn  于 2023-05-12  发布在  其他
关注(0)|答案(1)|浏览(112)

此问题已在此处有答案

Could pandas use column as index?(4个答案)
6天前关闭。
我有一个dataframe,看起来像这样:

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

如何更改dataframe的索引,使其标记为日期列,即

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
yhuiod9q

yhuiod9q1#

你可以使用pandas dataframe的set_index()方法来改变dataframe的索引。下面是实现它的代码:

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看起来像这样:

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

相关问题