[Python数据科学手册]2.4聚合,最小值最大值其他值

619 阅读1分钟
import numpy as np 

#数组求和
L = np.random.random(100)
sum(L)
np.sum(L) #稍微快一点

#最大最小值
big_array = np.random.random(1000000)
min(big_array),max(big_array)
np.min(big_array),np.max(big_array)
# 一种更简洁的语法形式是数 组对象直接调用这些方法:
print(big_array.min(), big_array.max(), big_array.sum())

#多维度聚合
M = np.random.random((3,4))
print(M)
# 每一个 NumPy 聚合函数将会返回对整个数组的聚合结果
M.sum()
#聚合函数还有一个参数,用于指定沿着哪个轴的方向进行聚合。
# 例如,可以通过指定 axis=0 找到每一列的最小值
M.min(axis=0)
#找到每一行的最大值
M.max(axis=1)

#用Pandas来读文件并抽取身高信息
import pandas as  pd 
data = pd.read_csv('D:\president_heights.csv')
heights = np.array(data['height(cm)'])
print(heights)

print("Mean height:       ", heights.mean()) #平均       
print("Standard deviation:", heights.std()) #标准差       
print("Minimum height:    ", heights.min())        
print("Maximum height:    ", heights.max())

print("25th percentile:   ", np.percentile(heights, 25)) #percentile百分率       
print("Median:            ", np.median(heights)) #中位数       
print("75th percentile:   ", np.percentile(heights, 75))

# %matplotlib inline
import matplotlib.pyplot as plt 
import seaborn;seaborn.set() #设置绘图风格

plt.hist(heights)        
plt.title('Height Distribution of US Presidents')        
plt.xlabel('height (cm)')        
plt.ylabel('number')