# numpy数组(4)-二维数组

python创建二维 list 的方法是在 list 里存放 list :

l = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]

numpy可以直接创建一个二维的数组:

import numpy as np
l = np.array([
[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]
])

numpy二维数组获取某个值:

[a, b] :  a 表示行索引, b 表示列索引,就是获取第 a 行第 b个元素

print l[1, 3]

# 8

print(l[1:3, 2:4])
# 取第1-3行,第2-4列的数据
# 结果:
[[ 7  8]
[11 12]]

print(l[1, :])

# 结果:
[5 6 7 8]
print(l[:, 3])

# 结果:
[4 8 12 16]

print(l.mean())

# 结果:
8.5

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

# 结果:
[[ 2  3  4]
[ 6  7  8]
[10 11 12]]

# 假设有如下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 mean_riders_for_max_station(ridership):
max_index = ridership[0, :].argmax()                     # 获取第一天(第0行)的最大值的索引
mean_for_max = ridership[:, max_index].mean()            # 通过获取的索引,获取对应列,取平均值
overall_mean = ridership.mean()
return (overall_mean, mean_for_max)

print(mean_riders_for_max_station(ridership))

# 结果:
(2342.6, 3239.9)

posted @ 2018-06-27 23:04  诗&远方  阅读(6070)  评论(0编辑  收藏  举报