时间数据处理/数组的轴向汇总
案例:统计每个周一、周二、...、周五的收盘价的平均值,并放入一个数组。
# 统计周一至周五的收盘价的均值 import datetime as dt import numpy as np # 转换器函数:将日-月-年格式的日期字符串转换为星期 def dmy2wday(dmy): # 把日月年转周N dmy = str(dmy, encoding='utf-8') date = dt.datetime.strptime(dmy, '%d-%m-%Y').date() wday = date.weekday() # 用 周日 return wday wdays, closing_prices = \ np.loadtxt('aapl.csv', delimiter=',', usecols=(1, 6), unpack=True, converters={1: dmy2wday}) print(wdays) """ [4. 0. 1. 2. 3. 4. 0. 1. 2. 3. 4. 0. 1. 2. 3. 4. 1. 2. 3. 4. 0. 1. 2. 3. 4. 0. 1. 2. 3. 4.] """ # 掩码[wdays==0] ave_closing_prices = np.zeros(5) for wday in range(ave_closing_prices.size): ave_closing_prices[wday] = np.mean(closing_prices[wdays == wday]) # ave_closing_prices[wday] = closing_prices[wdays == wday].mean() print(ave_closing_prices) # [351.79 350.635 352.13666667 350.89833333 350.02285714] # 数组的轴向汇总 prices = closing_prices.reshape(6, 5) print(prices) """ [[336.1 339.32 345.03 344.32 343.44] [346.5 351.88 355.2 358.16 354.54] [356.85 359.18 359.9 363.13 358.3 ] [350.56 338.61 342.62 342.88 348.16] [353.21 349.31 352.12 359.56 360. ] [355.36 355.76 352.47 346.67 351.99]] """ def func(ary): # 数组处理函数 return np.mean(ary),np.std(ary) r = np.apply_along_axis(func, 0, prices) print(np.round(r, 2)) """ [[349.76 349.01 351.22 352.45 352.74] 均值 [ 6.97 7.74 5.86 8.04 5.7 ]] 标准差 """ for wday, ave_closing_price in zip( ['MON', 'TUE', 'WED', 'THU', 'FRI'], ave_closing_prices): print(wday, np.round(ave_closing_price, 2)) """ MON 351.79 TUE 350.64 WED 352.14 THU 350.9 FRI 350.02 """
def func(data): pass #func 处理函数 #axis 轴向 [0,1] #array 数组 np.apply_along_axis(func, axis, array)
沿着数组中所指定的轴向,调用处理函数,并将每次调用的返回值重新组织成数组返回。