pandas dataframe不会重新排序列

时间:2018-05-28 21:03:51

标签: python pandas dataframe quandl

我正在编写一个脚本来从Quandl中检索数据,该数据在保存之前操纵数据。我坚持一步,我喜欢使用像df = df[['Code','Date','Open','High','Low','Close','Volume']]这样的pandas重新排序我的列,或者用简单的术语,与代码交换日期

我认为这是因为系统自动将Date设置为索引,但追溯说['Date'] not in index

我观察到df.index = df.index.strftime('%Y%m%d'),打印2输出时,日期标签会从数据框中删除。如果我对此行发表评论,则错误代码仍然存在。

我尝试插入df.set_index('Code')以查看更改索引是否会有所帮助但是没有。

有谁知道这里的问题是什么?

代码

myArr = ['CHRIS/CME_AD1']
cDate=int(time.strftime("%Y%m%d"))

# get quandl data, edit dataframe & save to csv
for qCode in myArr:
    data = qdl.get(qCode, start_date=StartDate)
    df = pd.DataFrame(data)
 #   df.to_dict()
    qID=(str(qCode[qCode.find('/')+1:]))
    print(df)

# format data & save
    df.insert(loc=0, column='Code', value=qID)
    df=df.drop(columns=['Change','Settle','Previous Day Open Interest'])
    df.rename(columns={'Last':'Close'}, inplace=True)  
    df.index = df.index.strftime('%Y%m%d')
    print(df) 
    df = df[['Code','Date','Open','High','Low','Close','Volume']] #reorder columns
    df.to_csv(path + qID + '_' + str(cDate) + '.txt', sep=',', index=True, header=1) 
print('Quandl Download Complete')

回溯

Traceback (most recent call last):
  File "\\progsql\SQL\Script\Python\EOD_Quandl - Copy.py", line 29, in <module>
    df = df[['Code','Date','Open','High','Low','Close','Volume']] #reorder columns
  File "C:\Python35\lib\site-packages\pandas\core\frame.py", line 2679, in __getitem__
    return self._getitem_array(key)
  File "C:\Python35\lib\site-packages\pandas\core\frame.py", line 2723, in _getitem_array
    indexer = self.loc._convert_to_indexer(key, axis=1)
  File "C:\Python35\lib\site-packages\pandas\core\indexing.py", line 1327, in _convert_to_indexer
    .format(mask=objarr[mask]))
KeyError: "['Date'] not in index"

打印1 - 来自Quandl

              Open             ...              Previous Day Open Interest
Date                           ...                                        
2018-05-10  0.7460             ...                                159970.0
2018-05-11  0.7534             ...                                164459.0
2018-05-14  0.7543             ...                                167173.0
2018-05-15  0.7526             ...                                169622.0
2018-05-16  0.7473             ...                                170863.0
2018-05-17  0.7516             ...                                164165.0
2018-05-18  0.7513             ...                                164628.0
2018-05-21  0.7529             ...                                161673.0
2018-05-22  0.7586             ...                                147136.0
2018-05-23  0.7575             ...                                147454.0
2018-05-24  0.7568             ...                                153308.0
2018-05-25  0.7578             ...                               151199.0

[12 rows x 8 columns]

打印2 - 操作后

             Code    Open    High     Low   Close    Volume
20180510  CME_AD1  0.7460  0.7540  0.7455  0.7534  125257.0
20180511  CME_AD1  0.7534  0.7567  0.7522  0.7538   93512.0
20180514  CME_AD1  0.7543  0.7565  0.7525  0.7529   72806.0
20180515  CME_AD1  0.7526  0.7538  0.7449  0.7471  129077.0
20180516  CME_AD1  0.7473  0.7524  0.7448  0.7514  125867.0
20180517  CME_AD1  0.7516  0.7548  0.7498  0.7509  108841.0
20180518  CME_AD1  0.7513  0.7529  0.7489  0.7511   87656.0
20180521  CME_AD1  0.7529  0.7588  0.7504  0.7583  118843.0
20180522  CME_AD1  0.7586  0.7607  0.7567  0.7576  104227.0
20180523  CME_AD1  0.7575  0.7584  0.7523  0.7558  149203.0
20180524  CME_AD1  0.7568  0.7584  0.7543  0.7579  102328.0
20180525  CME_AD1  0.7578  0.7591  0.7543  0.7549   85082.0

2 个答案:

答案 0 :(得分:0)

'Date'有数据框索引的名称,而不是其中一列,因此您无法将其与其他列“重新排序”。

答案 1 :(得分:0)

我花了一些时间研究pd.Dataframe.set_indexpd.Dataframe.reset_index的解决方案,但原始索引保持不变。

由于索引不能被视为一列而且df必须有一个索引,我提出了这样的想法: - 重命名索引 - 将其复制到列 - 重新排序列 - 使用to_csv

保存index=False

这有点长,但在这种情况下可以完成任务。

# format data & save  
    df.index.names = ['ID']
    df['Date'] = df.index
    df.insert(loc=0, column='Code', value=qID)
    df=df.drop(columns=['Change','Settle','Previous Day Open Interest'])
    df.rename(columns={'Last':'Close'}, inplace=True)  
    df.index = df.index.strftime('%Y%m%d')
    df = df[['Code','Date','Open','High','Low','Close','Volume']] #reorder columns
    df.to_csv(path + qID + '_' + str(cDate) + '.txt', sep=',', index=False, header=0) 

    print(df)