In [1]:
import numpy as np
In [2]:
# 我们使用转换函数,载入收盘价和日期数据
import datetime
def datestr2num(s):
return datetime.datetime.strptime(s, "%d-%m-%Y").toordinal()
dates, cp = np.loadtxt('AAPL.csv', delimiter=',', usecols=(1,6), converters={1:datestr2num}, unpack=True)
dates = dates.astype(int)
In [3]:
# 数据本身已经按照日期顺序排好,不过我们现在优先按照收盘价排序
# lexsort返回排序后的数组下标
indices = np.lexsort((dates, cp))
print "Indices:\n", indices
In [4]:
print ["%s %s" % (datetime.date.fromordinal(dates[i]), cp[i]) for i in indices]
In [6]:
# 生成5个随机数作为实部,5个随机数作为虚部
# 设置随机数种子为42
np.random.seed(42)
complex_numbers = np.random.random(5) + 1j * np.random.random(5)
print "Complex numbers:\n", complex_numbers
In [7]:
print "Sorted:\n", np.sort_complex(complex_numbers)
In [9]:
a = np.array([2,4,8])
np.argmax(a)
Out[9]:
In [10]:
b = np.array([np.nan, 2, 4])
np.nanargmax(b)
Out[10]:
argmin和nanargmin函数功能类似,只是换成最小值
In [11]:
np.argwhere(a <= 4)
Out[11]:
In [12]:
# 创建升序排列的数组
a = np.arange(5)
# 调用searchsorted函数
indices = np.searchsorted(a, [-2,7])
print "Indices", indices
In [13]:
# 使用insert函数构建完整的数组
print "The full array", np.insert(a, indices, [-2,7])
searchsorted函数为7和-2返回索引5和0.用这些索引作为插入位置,我们生成了数组[-2 0 1 2 3 4 7],这样就维持了数组的顺序。
In [14]:
a = np.arange(7)
# 生成选择偶数元素的条件变量
condition = (a%2) == 0
# 使用extract函数基于生成的条件从数组中抽取元素
print "Even numbers:\n", np.extract(condition, a)
In [15]:
print "Non zero:\n", np.nonzero(a)