文章目录
- 一、处理星期数据
- 二、apply_along_axis函数的用法
- 三、星期汇总案例
一、处理星期数据
1、datetime对象的weekday()方法
该方法将会用0到6这七个数字表示周一到周日
2、计算周一到周五数据平均值的三种方法
- 数组[关系表达式]:关系表达式的值是一个布尔型数组,其中为True的元素是数组中满足关系表达式的元素。以上下标运算的值就是从数组拣选与布尔数组中为True的元素相对于的元素。
- np.where(关系表达式):数组中满足关系表达式的元素的下标数组
- np.take(数组, 下标数组):数组中由下标数组所表示的元素的集合
3、按星期求均值案例
import numpy as np
import datetime as dt
def dmy2week(dmy):
dmy = str(dmy, encoding='utf-8')
date = dt.datetime.strptime(dmy, '%d-%m-%Y').date()
wdays = date.weekday()
return wdays
wdays, closing_prices = np.loadtxt(
'0=数据源/beer_price.csv', delimiter=',',
usecols=(0, 4), unpack=True,
converters={0: dmy2week}
)
ave_closing_prices = np.zeros(7)
for wday in range(ave_closing_prices.size):
ave_closing_prices[wday] = \
np.take(closing_prices, np.where(wdays == wday)).mean()
for wday, ave_closing_price in zip(
['Mon','Tue','Wed','Thu','Fri','Sta','Sun'],
ave_closing_prices):
print(wday, np.round(ave_closing_price, 2))
二、apply_along_axis函数的用法
1、格式
Y = numpy.apply_along_axis(函数, 轴向, 高维数组)
2、作用
再高维数组中沿着指向的轴向,提出低维子数组,作为参数传递给函数中,并将返回值按照同样的轴向组成新的数组返回给调用者。
3、轴向
二维:0是行方向,1是列方向
三维:0是页方向,1是行方向,2是列方向
4、练习
import numpy as np
def Func(x):
return x ** 2
X = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
Y1 = np.apply_along_axis(Func, 0, X)
print(Y1)
Y2 = np.apply_along_axis(Func, 1, X)
print(Y2)
三、星期汇总案例
1、目的
对每一个星期的数据进行汇总,将每个星期的星期一开盘价作为开盘价,每个星期的星期五的收盘价作为收盘价,整个星期的所有最高价中的最高价作为最高价,最低价作为最低价。这样就是将一个星期作为一个整体,分别求出各个星期整体的开盘价,最高价,最低价,收盘价了。
2、参考代码
import datetime as dt
import numpy as np
def dmy2wday(dmy):
dmy = str(dmy, encoding='utf-8')
date = dt.datetime.strptime(dmy, '%d-%m-%Y').date()
wday = date.weekday()
return wday
wdays, opening_prices, highest_prices, lowest_prices, closing_prices = np.loadtxt(
'0=数据源/beer_price.csv', delimiter=',',
usecols=(0, 1, 2, 3, 4), unpack=True,
converters={0: dmy2wday}
)
wdays = wdays[:16]
opening_prices = opening_prices[:16]
highest_prices = highest_prices[:16]
lowest_prices = lowest_prices[:16]
closing_prices = closing_prices[:16]
first_monday = np.where(wdays == 0)[0][0]
last_sunday = np.where(wdays == 4)[0][-1]
indices = np.arange(first_monday, last_sunday + 1)
indices = np.split(indices, 3)
def week_summary(indices):
opening_price = opening_prices[indices[0]]
highest_price = np.max(np.take(highest_prices, indices))
lowest_price = np.min(np.take(lowest_prices, indices))
closing_price = closing_prices[indices[-1]]
return opening_price, highest_price,\
lowest_price, closing_price
summaries = np.apply_along_axis(
week_summary, 1, indices
)
print(summaries)
3、参考结果
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)