2011-11-02 5 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을 사용하여 num을 다시 datetime 객체로 변환 할 수 있습니다. 그런 다음 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']}) 

objectISO_time DTYPE을 변환합니다. 이렇게하면 열이 먼저 float 값을 유지하고 나중에 문자열을 유지할 수 있습니다. astype (아래)은 복사본을 반환하므로 명시 적으로 copy을 호출 할 필요가 없습니다. 또한 copy을 호출 한 이후로, 메모리에 배열의 복사본 두 개를 보관하는 것이 문제가되지 않는다고 가정합니다. (메모리가 꽉 있다면 메모리가 문제가되지 않습니다 때문에, 우리는 np.savetxt가 더 편리합니다, csv로 모듈을 사용하는 대신 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 . 특히 modulenumpy 일 때 from module import *을 사용하지 않는 것이 좋습니다. 그것은뿐만 아니라이 어렵게 파이썬 내장 매크로를 호출 할 수 있도록 않습니다 파이썬 내장 기능의 수와 같은 abs, all, any, min, max, sum, round 등을 덮어뿐만 아니라 쉽게 보이는 코드를 작성 할 수 있습니다 맞지만 찾기 어렵거나 미묘한 버그가 있습니다.

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 
이 경우

,이 같은 시도
관련 문제