2011-11-02 23 views
1

我是新的python,並有一個基本的問題,我無法在網上找到解決方案。在Numpy中導出ISO日期

我有一個名爲IBTsample.txt表,包含:

  • 季節,ISO_time,經緯度,枚舉
  • 2009,2009-12-24 12:00:00,6.50,85.00, 2
  • 2009,2009-12-25 06:00:00,8.00,84.50,6
  • 2009,2009-12-25 00:00:00,7.00,84.50,4
  • 2009,2009- 12-24 18:00:00,6.50,85.00,3
  • 2009,2009-12-24 09:00:00,6.50,8 5.00,1
  • 2009,2009-12-25 03:00:00,7.00,84.50,5

我想要做的就是導入它作爲numpy的陣列,做一些處理(用於時間只是簡單地對記錄日期進行排序)並將處理後的表格導出爲新的.txt文件。

from numpy import * 
import pylab 

rawtable = loadtxt('IBTsample.txt', delimiter=',', skiprows=1, converters= {1:pylab.datestr2num},\ 
       dtype={'names':('Season','ISO_time','Latitude','Longitude','Enum'),\ 
         'formats':('uint16','float','float16','float16','uint8')}) 
sortable = (sort(rawtable, order=('ISO_time'))).copy() 
savetxt('IBTsorted.txt', sortable, fmt='%d,%.3f,%.1f,%.1f,%d') 

我有TI使用pylab.datestr2num功能輸入過程中卻找不到一個反函數導出的日期和時間的ISO格式。

任何幫助或想法都會很有幫助。

回答

3

您可以使用matplotlib.dates.num2date將數字轉換回日期時間對象。然後撥打isoformat()以ISO-8601格式的字符串獲取日期。

import numpy as np 
import matplotlib.dates as md 

def num2isodate(num): 
    result=md.num2date(num).isoformat() 
    return result 

rawtable = np.loadtxt(
    'IBTsample.txt', delimiter=',', skiprows=1, 
    converters= {1:md.datestr2num}, 
    dtype={'names':['Season','ISO_time','Latitude','Longitude','Enum'], 
      'formats':['uint16','float','f4','f4','uint8']}) 

轉換的ISO_time D型到object。這允許列首先保存浮點值,然後再保留字符串。請注意0​​(下面)返回一個副本,因此不再需要明確調用copy。另外,既然你叫copy,我假設在內存中保存兩個數組的副本不是問題。 (如果內存是緊張,我們可以使用CSV模塊,而不是使用np.savetxt寫入陣列行由行。但是,由於內存是沒有問題的,np.savetxt更方便。)

sortable = rawtable.astype({'names':['Season','ISO_time','Latitude','Longitude','Enum'], 
          'formats':['uint16','object','f4','f4','uint8']}) 
sortable = np.sort(sortable, order=('ISO_time')) 
sortable['ISO_time'] = [num2isodate(num) for num in sortable['ISO_time']] 
np.savetxt('IBTsorted.txt', sortable, fmt='%d,%s,%.1f,%.1f,%d') 

PS 。我建議不要使用from module import *,特別是當modulenumpy。它覆蓋了許多Python內建函數,如abs,all,any,min,max,sum,round等。這不僅使得它更難調用Python內置函數,而且還使得編寫代碼看起來很容易正確但包含難以發現或微妙的錯誤。

1

除了@ unutbu的回答,如果您使用的是最新版本的numpy(>= 1.7),則有一個本機日期dtype。

在這種情況下,嘗試這樣的事情:

import numpy as np 
import dateutil.parser 

rawtable = np.genfromtxt('test_in.txt', names=True, delimiter=',', 
       converters={1:dateutil.parser.parse}, 
       dtype=[np.uint16, np.datetime64, np.float, np.float, np.uint8]) 

sorttable = np.sort(rawtable, order=('ISO_time')) 

with open('test_out.txt', 'w') as outfile: 
    outfile.write(','.join(sorttable.dtype.names) + '\n') 
    np.savetxt(outfile, sorttable, fmt='%i,%r,%f,%f,%i') 

這產生了:

Season,ISO_time,Latitude,Longitude,Enum 
2009,2009-12-24 09:00:00,6.500000,85.000000,1 
2009,2009-12-24 12:00:00,6.500000,85.000000,2 
2009,2009-12-24 18:00:00,6.500000,85.000000,3 
2009,2009-12-25 00:00:00,7.000000,84.500000,4 
2009,2009-12-25 03:00:00,7.000000,84.500000,5 
2009,2009-12-25 06:00:00,8.000000,84.500000,6