前菜–Numpy

import numpy as np

1.1 数组方法

# 生成1 维数组
a = np.array([1,2,3,4])
a
array([1, 2, 3, 4])
#生成二维数组
a = np.array([
    [1,2,3,4],
    [5,6,7,8],
    [7,7,7,7]
])
a
array([[1, 2, 3, 4],
       [5, 6, 7, 8],
       [7, 7, 7, 7]])

·start 表示开始数字 为下确界 默认为0
·stop 表示结束的数 为上界
·step 表示公差 默认为1
·dtype 指定数据类型 默认inter32
因为start、step和dtype都有默认值,所以可以只写入stop

#下面创建一个从0到9的数组
np.arange(10)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
#创建首项为1 截止到10(不包含) 指定步长2
np.arange(1,10,2)
array([1, 3, 5, 7, 9])

·num 该等差数组的个数
·endpoint 序列中是否包含stop值,注意这里默认为true
explain:这个方法主要是我们知道首尾之后使用的,所以endpoint默认为true

#比如我们只知道一个数组首项为0,最后一项为10,且该数组有5个数
np.linspace(0,10,5)
array([ 0. ,  2.5,  5. ,  7.5, 10. ])
#将一个一维数组转为二维
np.arange(10).reshape(2,5)
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])
#都是1的数组可以使用np.ones来生成 参数为矩阵的形状
#可以用np.ones_like(a)来生成和a形状一样的数组
#默认为1维
np.ones(10) # 生成一维十个分量都为一的数组
np.ones((2,5)) #生成二维每个维度的五个等量都为一的数组

array([[1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.]])

同理,可以生成所需的全为零(zeros),没有初始化(empty),特定数(full)的数组

#创建五个范围在[0,1)之间的数据
#这里需要说明:random函数生成的范围为左闭右开
np.random.rand(5)
array([0.44632437, 0.81121282, 0.80482189, 0.41552902, 0.92565849])
#指定shape
np.random.rand(3,4)
array([[0.38044668, 0.18780878, 0.88673987, 0.5911139 ],
       [0.93546119, 0.64607342, 0.62441079, 0.74648861],
       [0.5757769 , 0.16007626, 0.55954991, 0.55501118]])
#randint(low,high,(shape))生成随机整数 区间[low,high)
#low默认为0
np.random.randint(1,10,(3,4))
array([[9, 7, 8, 9],
       [5, 9, 5, 1],
       [3, 7, 9, 6]])
#uniform()生成在[low,high)之间均匀分布的数字
np.random.uniform(1,10,(3,4))
array([[6.03188774, 3.39992438, 3.56467481, 2.58653308],
       [2.85072574, 2.46446551, 6.80989601, 1.84529343],
       [2.98288733, 7.39698989, 7.89446111, 7.4762518 ]])
#randn()生成的数据具有标准正态分布 均值为0,方差为1
np.random.randn(3,4)
array([[ 0.82166166,  0.44499244, -1.82220382, -0.04496252],
       [ 0.31283332, -1.4152152 ,  1.12381001,  1.88690788],
       [-0.121892  , -0.48383337, -0.19617823, -2.80674969]])
#normal() 可以指定均值和标准差
np.random.normal(5,10,(3,4))
array([[14.78332891, 23.10401466, -2.25248365,  6.21926006],
       [ 8.4929957 ,  3.29216256, -3.71472177,  1.58433458],
       [-4.55193955,  3.40607897, -9.00472229,  6.96018844]])
#choice(给定数组,结果的shape) 从给定的数组中,产生随机结果
np.random.choice(5,(2,3))
#等同于 np.random.choice(0,5,3)
array([[3, 4, 1],
       [0, 4, 2]])
#shuffle 把一个数组的分量随机排列
(array([[0, 1, 2, 3, 4],
        [5, 6, 7, 8, 9]]),
 array([[0, 1, 2, 3, 4],
        [5, 6, 7, 8, 9]]))

1.2 数组属性:

#生成二维数组
a = np.array([
    [1,2,3,4],
    [5,6,7,8],
    [7,7,7,7]
])
a
array([[1, 2, 3, 4],
       [5, 6, 7, 8],
       [7, 7, 7, 7]])
# ndim 返回一个数组的维度
a.ndim
#shape 返回一个元组 array的维度和每个维度有几个分量
#系数矩阵的形状
a.shape
(3, 4)
#dtype array中元素的数据类型
a.dtype
dtype('int32')
#size 返回一个array中所有元素的加总值
a.size
12
#itemsize 返回数组中每个元素的大小
a.itemsize

1.3 数组索引 大致和原生List相同

#首先创建一个数组
x = np.arange(10)
#取出x中的第一个元素的值
#注意:缩影是从0开始的
x[0]
# 取值2-8
# 数组的数也是从0开始的,所以2的索引为2
# 又因为8靠近数组的上界,所以索引可以用-2
# 但是当我们使用区间来表示索引的时候 区间的范围是左闭右开
x[2:-1]
array([2, 3, 4, 5, 6, 7, 8])
#再生成一个多维数组
y = np.arange(20).reshape(4,5)
y
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])
y.ndim
#取第二行第一列的数据
#行列的索引也是从0开始
y[0,0]
#取所有第二行的元素
y[1]
array([5, 6, 7, 8, 9])
#取所有第二列的元素
y[:,1]
array([ 1,  6, 11, 16])
x[:2] = 666 #修改数表中的元素是索引最大的作用
x
array([666, 666,   2,   3,   4,   5,   6,   7,   8,   9])
y[1,0] = 1
y
array([[ 0,  1,  2,  3,  4],
       [ 1,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

需要注意的是:基础切片产生的是view,而修改view会对原来的数组产生影响

可以使用以下方法来切片
slice object (constructed by start:stop:step notation inside of brackets)(等差数列) i:j:k
an integer
a tuple of slice objects and integers.

Ellipsis and newaxis objects can be interspersed with these as well.(维度索引)

There are some tools to facilitate the easy matching of array shapes with expressions and in assignments.

expands to the number of : objects needed for the selection tuple to index all dimensions.

所以 … 把 : 拓展到了所有维度的index上,

x = np.array([
    [[1],[2],[3]],
    [[4],[5],[6]]
])
x[...,0]
array([[1, 2, 3],
       [4, 5, 6]])
x[:,:,0]
array([[1, 2, 3],
       [4, 5, 6]])

expand the dimensions of the resulting selection by one unit-length dimension.The added dimension is the position of the newaxis object in the selection tuple.

newaxis = None
new一个axis,添加一个维度.

x[:, np.newaxis, :, :].shape # 原来是2,3,1 现在添加了一个维度
(2, 1, 3, 1)
x[:, None, :, :].shape # 功能相同
(2, 1, 3, 1)

This can be handy to combine two arrays in a way that otherwise would require explicit reshaping operations. For example:

x = np.arange(5)
a = x[:,np.newaxis]
b = x[np.newaxis,:]
# x[:,np.newaxis] + x[np.newaxis,:]
a , b
(array([[0],
        [1],
        [2],
        [3],
        [4]]),
 array([[0, 1, 2, 3, 4]]))
a + b
array([[0, 1, 2, 3, 4],
       [1, 2, 3, 4, 5],
       [2, 3, 4, 5, 6],
       [3, 4, 5, 6, 7],
       [4, 5, 6, 7, 8]])

学习之前,我们先来看看官方文档上的一个tip

Advanced indexing always returns a copy of the data (contrast with basic slicing that returns a view).

返回的是一个副本,在副本上操作不会改变原来的array

The definition of advanced indexing means that x[(1, 2, 3),] is fundamentally different than x[(1, 2, 3)]. The latter is equivalent to x[1, 2, 3] which will trigger basic selection while the former will trigger advanced indexing. Be sure to understand why this occurs.

Also recognize that x[[1, 2, 3]] will trigger advanced indexing, whereas due to the deprecated Numeric compatibility mentioned above, x[[1, 2, slice(None)]] will trigger basic slicing.

Thus, x[ind1, …, ind2,:] acts like x[ind1][…, ind2, :] under basic slicing.This not true for advanced indexing.

x = np.arange(64).reshape(4,4,4) # 三维数组
a = x[(1,2,3),]#在最高维度上的index是1,2,3
b = x[(1,2,3)]#在第三维度上的index是1,第二维度上的index是2,第一维度上的index是3
c = x[[1,2,3]]
d = x[1][2][3],
#d = x[[1,2,slice(None)]]#弃用了的数字兼容性
x,a,b,c,d
(array([[[ 0,  1,  2,  3],
         [ 4,  5,  6,  7],
         [ 8,  9, 10, 11],
         [12, 13, 14, 15]],

        [[16, 17, 18, 19],
         [20, 21, 22, 23],
         [24, 25, 26, 27],
         [28, 29, 30, 31]],

        [[32, 33, 34, 35],
         [36, 37, 38, 39],
         [40, 41, 42, 43],
         [44, 45, 46, 47]],

        [[48, 49, 50, 51],
         [52, 53, 54, 55],
         [56, 57, 58, 59],
         [60, 61, 62, 63]]]),
 array([[[16, 17, 18, 19],
         [20, 21, 22, 23],
         [24, 25, 26, 27],
         [28, 29, 30, 31]],

        [[32, 33, 34, 35],
         [36, 37, 38, 39],
         [40, 41, 42, 43],
         [44, 45, 46, 47]],

        [[48, 49, 50, 51],
         [52, 53, 54, 55],
         [56, 57, 58, 59],
         [60, 61, 62, 63]]]),
 27,
 array([[[16, 17, 18, 19],
         [20, 21, 22, 23],
         [24, 25, 26, 27],
         [28, 29, 30, 31]],

        [[32, 33, 34, 35],
         [36, 37, 38, 39],
         [40, 41, 42, 43],
         [44, 45, 46, 47]],

        [[48, 49, 50, 51],
         [52, 53, 54, 55],
         [56, 57, 58, 59],
         [60, 61, 62, 63]]]),
 27)
x = np.arange(10)
indexs = np.array([
    [0,2],
    [1,3]
])
x[indexs]
x
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

二维数组中的使用方法
y[[r_1,r_2,……,r_n],[c_1,c_2,……,c_n]]
r_i为第i个元素的行,c_i为第i个元素的列

y = np.arange(20).reshape(4,5)
y
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])
y[[0,2],[0,1]]
array([ 0, 11])
x = np.arange(10)
x > 6
x[ x > 6]#返回x>6为真时索引对应的元素
array([7, 8, 9])

谈到布尔我们就不得不谈一下布尔运算符号 & |

x = np.arange(10)
condition = (x%2 == 0) | (x > 7)
x[condition]
array([0, 2, 4, 6, 8, 9])

1.4数组运算

#基础运算和矩阵是一致的
#但是两个数组的乘法是单纯的对应相乘
# 2*3的矩阵和3*2的矩阵运算
a = np.arange(6,12).reshape(2,3)
b = np.random.randint(2,10,(2,3))
a,b
(array([[ 6,  7,  8],
        [ 9, 10, 11]]),
 array([[2, 8, 6],
        [8, 7, 9]]))
a * b
array([[12, 56, 48],
       [72, 70, 99]])
#sum求和函数
#prod乘积
#cumsum累加
#cumprod累乘
#min最小值
#max最大值
#quantile 获取四分位的数值
#median中位数
#mean平均数
#std标准差
#var方差
#average(数据,权值)加权平均

1.5 axis参数

axis = 0 表示行,axis = 1 表示列
对于sum/mean/media等聚合函数

  • axis = 0 表示把行消解掉 跨行运算
  • axis = 1 表示把列消解掉,跨列运算

1.6 添加维度

np.expand_dims(arr,axis = 0|1)

1.7 数组合并

a = np.arange(6).reshape(2,3)
b = np.arange(6,18).reshape(4,3)

我们发现a,b列数相同

np.concatenate([a,b])
np.vstack([a,b])
np.row_stack([a,b])
a = np.arange(12).reshape(3,4)
b = np.arange(12,18).reshape(3,2)

我们发现a,b行数相同

np.concatenate([a,b],axis=1)
np.hstack([a,b])
np.column_stack([a,b])

Original: https://www.cnblogs.com/epictus/p/littlenumpy.html
Author: epictus
Title: 前菜–Numpy



相关阅读

Title: 【题解】Drainage Ditches

在农民约翰的农场里,每当下雨,贝西最喜欢的三叶草就会积水。这意味着草被淹了,草还需要很长时间才能继续生长。因此,农民约翰建造了一个排水系统,以避免贝西的草被洪水淹没(别担心,雨水会流到附近的一条小溪里)。作为一流的技术员,农民约翰在每个排水沟的一端安装了一个控制器,这样他就可以控制流入排水沟的水的流量。

[En]

On farmer John’s farm, whenever it rains, Bessie’s favorite clover grass accumulates a pool of water. This means that the grass is flooded, and it will take a long time for the grass to continue to grow. So farmer John built a drainage system to save Bessie’s grass from being flooded (don’t worry, Rain Water will flow to a nearby stream). As a first-rate technician, farmer John has installed a controller at one end of each gutter so that he can control the flow of water into the gutter.

农民约翰知道每个排水口每分钟能流多少水,以及排水系统的确切布局(一个以池塘为起点,以溪流为终点的网络)。重要的是要注意,有时从一个地方到另一个地方有不止一个排水沟。

[En]

Farmer John knows how much water each drain can flow per minute, and the exact layout of the drainage system (a network that starts with a pool and ends with a stream). It is important to note that sometimes there is more than one drain from one place to another.

基于该信息,计算从池到流的最大流量。对于给定的每条边沟,雨水只能向一个方向流动。请注意,雨水可能会出现环状流动。

[En]

Based on this information, the maximum flow from the pool to the stream is calculated. For each gutter given, Rain Water can only flow in one direction. Note that the annular flow of Rain Water may occur.

第一行:两个用空格分开的整数 (N)((0 \le N \le 200))和 (M)((2 \le M \le 200))。(N) 是农夫 John 已经挖好的排水沟的数量,(M) 是排水沟交叉点的数量。交点 (1) 是水潭,交点 (M) 是小溪。

第二行到第 (N + 1) 行:每行有三个整数,(S_i, E_i, C_i)。(S_i) 和 (E_i)((1 \le S_i, E_i \le M))指明排水沟两端的交点,雨水从 (S_i) 流向 (E_i)。(C_i)((0 \le C_i \le {10}^7))是这条排水沟的最大容量。

输出一个整数,即排水的最大流量。

5 4
1 2 40
1 4 20
2 4 20
2 3 30
3 4 10
50

题目翻译来自NOCOW。

USACO Training Section 4.2

【数据范围】

对于 (100 \%) 的数据,(0 \le N, M \le 200),(0 \le C_i \le {10}^7)。

裸最大流板子

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
#include<cstring>
using namespace std;
#define int long long
const int N=10100,M=200100,inf=1e8;

int n,m,S,T;
int q[N],cur[N],h[N],d[N],idx;
int e[M],ne[M],f[M];

inline void add(int a,int b,int c)
{
    e[idx]=b,f[idx]=c,ne[idx]=h[a],h[a]=idx++;
    e[idx]=a,f[idx]=0,ne[idx]=h[b],h[b]=idx++;
}
inline bool bfs()
{
    int tt=0,hh=0;
    memset(d,-1,sizeof d);
    q[0]=S,d[S]=0,cur[S]=h[S];

    while(hh<=tt) { int t="q[hh++];" for(int i="h[t];~i;i=ne[i])" ver="e[i];" if(d[ver]="=-1&&f[i])" d[ver]="d[t]+1;" cur[ver]="h[ver];" if(ver="=T)" return true; q[++tt]="ver;" } false; find(int u,int limit) if(u="=T)" limit; flow="0;" cur[u]="i;" if(!t) f[i]-="t;" f[i^1]+="t;" flow+="t;" flow; dinic() ans="0,flow;" while(bfs()) while(flow="find(S,inf))" ans+="flow;" ans; signed main() while(cin>>n>>m)
    {
        S=1,T=m;
        memset(h,-1,sizeof h);
        idx=0;
        for(int i=1;i<=n;i++) { int u,v,c; cin>>u>>v>>c;
            add(u,v,c);
        }
        cout<<dinic()<<endl; } return 0; < code></dinic()<<endl;></=n;i++)></=tt)></cstring></queue></algorithm></iostream></cstdio>

Original: https://www.cnblogs.com/watasky/p/16636822.html
Author: watasky
Title: 【题解】Drainage Ditches

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/308198/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

最近整理资源【免费获取】:   👉 程序员最新必读书单  | 👏 互联网各方向面试题下载 | ✌️计算机核心资源汇总