最值

最值

np.max() np.min() np.ptp(): 返回一个数组中最大值/最小值/极差 

import numpy as np
# 产生9个介于[10, 100)区间的随机数
a = np.random.randint(10, 100, 9)
print(a)
print(np.max(a), np.min(a), np.ptp(a))

# [92 12 30 22 37 76 85 56 66]
# 92 12 80

np.argmax() np.argmin(): 返回一个数组中最大/最小元素的下标

print(np.argmax(a), np.argmin(a))

# 0 1

np.maximum() np.minimum(): 将两个同维数组中对应元素中最大/最小元素构成一个新的数组

import numpy as np

# 产生9个介于[10, 100)区间的随机数
a = np.random.randint(10, 100, 9)
b = np.random.randint(10, 100, 9)
print(a)
# [13 59 93 98 53 50 12 73 51]
print(b)
# [34 90 68 84 46 99 74 11 70]
print(np.maximum(a, b))
# [34 90 93 98 53 99 74 73 70]
print(np.minimum(a, b))
# [13 59 68 84 46 50 12 11 51]

 

a=np.arange(1,10).reshape(3,3)
b = np.arange(1,10)[::-1].reshape(3,3)
print(np.maximum(a,b))
"""
[[9 8 7]
 [6 5 6]
 [7 8 9]]
"""
print(np.minimum(a,b))
"""
[[1 2 3]
 [4 5 4]
 [3 2 1]]
"""

案例:评估AAPL股票的波动性。

import numpy as np
import datetime as dt

def dmy2ymd(dmy):
  """
  把日月年转年月日
  :param day:
  :return:
  """
  dmy = str(dmy, encoding='utf-8')
  t = dt.datetime.strptime(dmy, '%d-%m-%Y')
  s = t.date().strftime('%Y-%m-%d')
  return s


dates, opening_prices, \
highest_prices, lowest_prices, \
closing_prices ,volumes= \
  np.loadtxt('aapl.csv',
             delimiter=',',
             usecols=(1, 3, 4, 5, 6,7),
             unpack=True,
             dtype='M8[D],f8,f8,f8,f8,f8',
             converters={1: dmy2ymd})  # 日月年转年月日

#30天的最大震荡幅度
max_price = np.max(highest_prices)
min_price = np.min(lowest_prices)
print(min_price,'~',max_price)
# 333.53 ~ 364.9

#哪一天是最高价,哪一天是最低价
max_ind = np.argmax(highest_prices)
min_ind = np.argmin(lowest_prices)
print('max',dates[max_ind])#max 2011-02-16
print('min',dates[min_ind])#min 2011-01-28

 

posted @ 2019-09-04 12:58  maplethefox  阅读(519)  评论(0编辑  收藏  举报