numpy数组(5)-二维数组的轴

numpy的mean(),std()等方法是作用于整个numpy数组的,如果是二维数组的话,也是整个数组,包括所有行和列,但我们经常需要它仅作用于行或者列,而不是整个二维数组,这个时候,可以定义轴axis:

axis=0表示作用于

axis=1表示作用于

以sum()求和方法为例:

import numpy as np

a = np.array([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
])
    
print a.sum()
# 45

print a.sum(axis=0)
# 表示对各个列求和
# [12 15 18] print a.sum(axis=1)
# 表示对各个行求和
# [6 15 24]

一个综合栗子:

# 假设有如下5个地铁站10天的客流数据
ridership = np.array([
    [   0,    0,    2,    5,    0],
    [1478, 3877, 3674, 2328, 2539],
    [1613, 4088, 3991, 6461, 2691],
    [1560, 3392, 3826, 4787, 2613],
    [1608, 4802, 3932, 4477, 2705],
    [1576, 3933, 3909, 4979, 2685],
    [  95,  229,  255,  496,  201],
    [   2,    0,    1,   27,    0],
    [1438, 3785, 3589, 4174, 2215],
    [1342, 4043, 4009, 4665, 3033]
])

首先计算各个车站每天的客流平均值,从中找出最大和最小值:

def min_and_max_riders_per_day(ridership):
    mean_ridership_per_station = ridership.mean(axis=0)
    max_daily_ridership = mean_ridership_per_station.max()     
    min_daily_ridership = mean_ridership_per_station.min()     
    return (max_daily_ridership, min_daily_ridership)
    
print(min_and_max_riders_per_day(ridership))    

# 结果
(3239.9, 1071.2)
原文地址:https://www.cnblogs.com/liulangmao/p/9236562.html