Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
545 views
in Technique[技术] by (71.8m points)

numpy - TypeError when using Matplotlib's strpdate2num with Python 3.2

In my current project I want to read some experimental data from a text file into Python using the following code:

import numpy as np
from matplotlib.dates import strpdate2num

data = np.recfromtxt('example.txt',
                 comments='#',
                 delimiter=';',
                 names=('time', 't_ref', 't_s', 't_amb1', 't_amb2', 't_amb3')
                 ,converters={'time': strpdate2num('"%d.%m.%Y %H:%M:%S"')}
                 )

with example.txt looking like

"04.10.2012 08:15:27";14.4;16;12.78;12.65;12.52
"04.10.2012 08:15:37";14.4;16;12.78;12.65;12.5
"04.10.2012 08:15:47";14.4;16;12.78;12.62;12.5
"04.10.2012 08:15:57";14.4;15.9;12.78;12.65;12.52
...

In Python 2.7, all is well, but when I try to transfer the code in 3.2, I get a TypeError from strpdate2num() saying

TypeError: strptime() argument 0 must be str, not <class 'bytes'>

I am fairly new to Python, but my theory is that NumPy somehow stores the time-array internally as byte instead of string, which collides with the stricter handling of both since Python 3.

Long story short, do you have any idea what might be the cause how to fix that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is a workaround:

import numpy as np
import matplotlib.dates as mdates

def bytedate2num(fmt):
    def converter(b):
        return mdates.strpdate2num(fmt)(b.decode('ascii'))
    return converter

date_converter = bytedate2num("%d.%m.%Y %H:%M:%S")

data = np.recfromtxt('example.txt',
                     comments='#',
                     delimiter=';',
                     names=('time', 't_ref', 't_s', 't_amb1', 't_amb2', 't_amb3'),
                     converters={'time': date_converter})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...