重學python【numpy】

信小呆發表於2020-12-27
#-*- encoding:utf-8 -*-
#建立資料
import numpy as np
a = np.array([1, 2, 4])
b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b[1, 2] = 99
#獲取陣列的大小
print a.shape
print b.shape
#獲取陣列的型別
print a.dtype
print b
#建立結構陣列
persontype = np.dtype({
    'names': ['name', 'sex', 'chinese', 'math', 'english'],
    'formats': ['S32', 'S32', 'i', 'i', 'f']
})
people = np.array([("XiaoYu", "woman", "100", "90", "59"),
                   ("XiaoLin", "woman", "90", "10", "80"),
                   ("XiaoLi", "man", "43", "43", "99.9"),
                   ("LV", "non", "30", "90", "40.3")],dtype=persontype)
print people
#獲取所有哦姓名
names = people[:]["name"]
print names
#獲取語文的平均分數
chinese = people[:]["chinese"]
print np.mean(chinese)
#獲取數學的最大成績
math = people[:]["math"]
print np.amax(math)

#獲取一個陣列[1, 3, 5, 7, 9]
x1 = np.arange(1, 10, 2)
print x1
##線性等分向量
x2 = np.linspace(1, 9, 5)
print x2
#陣列之間的加減乘除、N次方,取餘
print np.add(x1, x2)
print np.subtract(x1, x2)
print np.multiply(x1, x2)
print np.divide(x1, x2)
print np.power(x1, 3)
print np.power(x1, x2)
print np.remainder(x1, x2)

#統計函式
b = np.array([[1, 2, 10], [4, 5, 6], [7, 8, 9]])
print np.amin(b)
#獲取每一列的最小值, 行話叫axis=0 軸
print np.amin(b, 0)
#獲取每一行的最小值
print np.amin(b, 1)
#獲取最大值和最小值之差
print np.ptp(b)
print np.ptp(b, 0)
print np.ptp(b, 1)
#統計陣列的百分位數,p=50相當於求平均值,p的範圍是0-100
print np.percentile(b, 100)
print np.percentile(b, 50, 0)
print np.percentile(b, 30, axis=1)
#統計陣列的中位數
print np.median(b)
print np.median(b, 0)
#計算加權平均書(加權平均數的計算方法,我小妹都知道~)
c = np.array([1, 2, 3, 4])
wts = np.array([1, 2, 3, 4])
print np.average(c)
print np.average(c, weights=wts)
#統計陣列的標準差,標準差是方差的算術平方根
print np.std(c)
#統計陣列的方差,每個數值與平均值之差的平方求和的平均
print np.var(c)
##做個驗證
print np.power(np.std(c), 2)

#陣列的排序,
d = np.array([[4, 6, 1], [3, 5, 2]])
#預設引數sort(a, axis=-1, kind=‘quicksort’, order=None),-1為陣列的最後一個軸,指定 quicksort、mergesort、heapsort 分別表示快速排序、合併排序、堆排序
print np.sort(d)
print np.sort(d, axis=None)
# 用 NumPy 統計下在語文、英語、數學中的平均成績、最小成績、最大成績、方差、標準差。
# 然後把這些人的總成績排序,得出名次進行成績輸出。
# 構建資料
studenttype = np.dtype({
    'names': ['name', 'chinese', 'english', 'math', 'total'],
    'formats': ['S32', 'f', 'f', 'f','f']
})
students = np.array([('lv', 66, 65, 30, 0),
                     ('ly', 95, 85, 98, 0),
                     ('bfd', 93, 92, 96, 0),
                     ('mi', 90, 88, 77, 0),
                     ('baidu', 80, 90, 90, 0)],dtype=studenttype)
#計算語文的平均成績
print np.mean(students[:]["chinese"])
#計算數學的最小值
print np.amin(students[:]["math"])
#計算英語的最大成績
print np.amax(students[:]["english"])
#計算語文的方差
print np.var(students[:]["chinese"])
#語文的標準差
print np.std(students[:]["chinese"])
print "======總成績排序======="
print students[:]["chinese"]
students[:]["total"] = np.add(np.add(students[:]["chinese"], students[:]["math"]), students[:]["english"])
print np.sort(students,order="total")

不要太在意別人的評價,做自己喜歡的事情就好~溫故而知新嘛

相關文章