Numpy日常积累

阅读书籍 NumPy Beginner’s Guide [Second Edition],一些关于使用Numpy的笔记。

1. ravel and flatten

参考这里

The difference is that flatten always returns a copy and ravel returns a view of the original array whenever possible. This isn’t visible in the printed output, but if you modify the array returned by ravel, it may modify the entries in the original array. If you modify the entries in an array returned from flatten this will never happen. ravel will often be faster since no memory is copied, but you have to be more careful about modifying the array it returns.

2. reshape and resize

The resize method works just like the reshape method, but modifies the
array it operates on

即,resize改变操作的对象,而reshape不改变。

3. Dates

关于np.loadtxt函数导入日期的问题。

3.1 converters

converters : dict, optional
A dictionary mapping column number to a function that will convert
that column to a float. E.g., if column 0 is a date string:
converters = {0: datestr2num}. Converters can also be used to
provide a default value for missing data (but see also genfromtxt):
converters = {3: lambda s: float(s.strip() or 0)}. Default: None.

3.2 binary to str

首先,我们运行:

1
dates, close=np.loadtxt('data.csv', delimiter=',', usecols=(1,6), unpack=True)

结果报错:

ValueError: could not convert string to float: b’28-01-2011’

于是我们编写指定日期格式的函数,再次导入

1
2
3
4
5
6
7

def datestr2num(s):
return datetime.strptime(s, "%d-%m-%Y").date().weekday()

dates, close=np.loadtxt('data.csv', delimiter=',', usecols=(1,6),
converters={1: datestr2num}, unpack=True)


还是报错:

TypeError: strptime() argument 1 must be str, not bytes

这次是因为日期列是二进制的格式,而我们的strptime要求参数是字符型。
修改datestr2num函数即可。继续运行:

1
2
3
4
5
6

def datestr2num(s):
return datetime.strptime(s.decode('ascii'), "%d-%m-%Y").date().weekday()

dates, close=np.loadtxt('data.csv', delimiter=',', usecols=(1,6),
converters={1: datestr2num}, unpack=True)

这次OK了!

参考:NumPy Beginner’s Guide [Second Edition] stackoverflow

4. argmax & argmin

也就是说,在使用argmax[argmin]时,我们一定注意数组中没有nan,否则我们将会得到错误的结果而找不出原因。

击蒙御寇