如何在将字典转换为数据帧时设置索引?

时间:2016-12-18 09:22:13

标签: python pandas dictionary

我有一个类似下面的字典

defaultdict(list,
        {'Open': ['47.47', '47.46', '47.38', ...],
         'Close': ['47.48', '47.45', '47.40', ...],
         'Date': ['2016/11/22 07:00:00', '2016/11/22 06:59:00','2016/11/22 06:58:00', ...]})

我的目的是将此字典转换为数据框并设置'日期'键值作为数据帧的索引。

我可以通过以下命令来完成这项工作

df = pd.DataFrame(dictionary, columns=['Date', 'Open', 'Close'])

     0  Date                  Open    Close
     1  2016/11/22 07:00:00   47.47   47.48
     2  2016/11/22 06:59:00   47.46   47.45
     3  2016/11/22 06:58:00   47.38   47.38

df.index = df.Date

     Date                  Date                  Open    Close
     2016/11/22 07:00:00   2016/11/22 07:00:00   47.47   47.48
     2016/11/22 06:59:00   2016/11/22 06:59:00   47.46   47.45
     2016/11/22 06:58:00   2016/11/22 06:58:00   47.38   47.38

但是,我有两个' Date'列,其中一个是索引,另一个是原始列。

有没有办法设置索引,而将字典转换为数据帧,而不会像下面那样重叠列?

     Date                  Close       Open
     2016/11/22 07:00:00   47.48       47.47
     2016/11/22 06:59:00   47.45       47.46
     2016/11/22 06:58:00   47.38       47.38

感谢您阅读本文! :)

1 个答案:

答案 0 :(得分:12)

使用set_index

df = pd.DataFrame(dictionary, columns=['Date', 'Open', 'Close'])  
df = df.set_index('Date')       
print (df)
                      Open  Close
Date                             
2016/11/22 07:00:00  47.47  47.48
2016/11/22 06:59:00  47.46  47.45
2016/11/22 06:58:00  47.38  47.40

或使用inplace

df = pd.DataFrame(dictionary, columns=['Date', 'Open', 'Close'])  
df.set_index('Date', inplace=True)       
print (df)
                      Open  Close
Date                             
2016/11/22 07:00:00  47.47  47.48
2016/11/22 06:59:00  47.46  47.45
2016/11/22 06:58:00  47.38  47.40

另一种可能的解决方案是按dict键过滤Date,然后按dictionary['Date']设置索引:

df = pd.DataFrame({k: v for k, v in dictionary.items() if not k == 'Date'}, 
                   index=dictionary['Date'], 
                   columns=['Open','Close'])  
df.index.name = 'Date'
print (df)
                      Open  Close
Date                             
2016/11/22 07:00:00  47.47  47.48
2016/11/22 06:59:00  47.46  47.45
2016/11/22 06:58:00  47.38  47.40