Datawhale Task01 预备知识 打卡

python基础

列表推导式与条件赋值

l = []
def my_func(x):
    return 2*x
for i in range(5):
    l.append(my_func(i))
l
[0, 2, 4, 6, 8]
#利用列表推导式进行简化
[my_func(i) for i in range(5)]
[0, 2, 4, 6, 8]
#支持多层嵌套
[m+'_'+n for m in ['cat','dog'] for n in ['huahua','xiaogou']]

['cat_huahua', 'cat_xiaogou', 'dog_huahua', 'dog_xiaogou']
#语法糖  语法糖(Syntactic sugar):计算机语言中特殊的某种语法  好看好用 

#条件赋值
value = 'cat' if 2>1 else 'dog'
value
'cat'
value1 = 'cat' if 3>4 else 'dog'
value1
'dog'
#例子
l = [1,2,3,4,5,6,7]
[i if i<= 5  else 5 for i in l]
[1, 2, 3, 4, 5, 5, 5]
ll= []
for i in l:
    if  i<= 5:
        ll.append(i)
    else:
        ll.append(5)
print(l1)
[1, 2, 3, 4, 5, 5, 5]

匿名函数与map用法

my_func = lambda x:2*x
my_func(3)
6
multi_para_func = lambda a,b:a+b
multi_para_func(1,2)
3
#在列表推导式中
[(lambda x: 2*x)(i) for i in range(5)]

[0, 2, 4, 6, 8]
#map函数
type(map(lambda x:2*x,range(5)))
map
list(map(lambda x:2*x,range(5)))
[0, 2, 4, 6, 8]
#对于多个值的函数映射,可以通过增加迭代对象实现
list(map(lambda x,y:str(x)+'_'+y,range(5),list('abcde')))
['0_a', '1_b', '2_c', '3_d', '4_e']
list('abcde')
['a', 'b', 'c', 'd', 'e']

zip对象与enumerate方法

#zip函数可以把多个可迭代对象打包成一个元组构成的可迭代对象,它返回了一个zip对象,通过tuple,list可以得到相应的打包结果  压缩函数
l1,l2,l3 = list('abc'),list('123'),list('www')
list(zip(l1,l2,l3))
[('a', '1', 'w'), ('b', '2', 'w'), ('c', '3', 'w')]
tuple(zip(l1,l2,l3))
(('a', '1', 'w'), ('b', '2', 'w'), ('c', '3', 'w'))
#往往在循环迭代的时候使用zip函数
for i,j,k in zip(l1,l2,l3):
    print(i,j,k)
a 1 w
b 2 w
c 3 w
#enumerate是一种特殊的打包,在迭代时绑定迭代元素的遍历序号
l = list('abcd')
for index,value in enumerate(l):
    print(index,value)
0 a
1 b
2 c
3 d
#zip 对象实现
for index,value in zip(range(len(l)),l):
    print(index,value)
0 a
1 b
2 c
3 d
range(len(l))
range(0, 4)
#对两个列表建立字典映射
dict(zip(l1,l2))
{'a': '1', 'b': '2', 'c': '3'}
#*zip 解压操作
zipped = list(zip(l1,l2,l3))
zipped
[('a', '1', 'w'), ('b', '2', 'w'), ('c', '3', 'w')]
list(zip(*zipped)) #对已经压缩的进行反向操作
[('a', 'b', 'c'), ('1', '2', '3'), ('w', 'w', 'w')]

numpy基础

数组的构造

import numpy as np
np.array([1,2,3])
array([1, 2, 3])
#等差数列
np.linspace(1,5,11)
array([1. , 1.4, 1.8, 2.2, 2.6, 3. , 3.4, 3.8, 4.2, 4.6, 5. ])
np.arange(1,5,2)
array([1, 3])
#特殊矩阵
np.zeros((2,3)) #两行三列
array([[0., 0., 0.],
       [0., 0., 0.]])
np.eye(3) #3*3的单位阵
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])
np.eye(3,k=1) #偏移主对角线1个单位的单位矩阵
array([[0., 1., 0.],
       [0., 0., 1.],
       [0., 0., 0.]])
np.full((2,3),10) #元组表示大小,两行三列,填充值是10
array([[10, 10, 10],
       [10, 10, 10]])
np.full((2,3),[4,5,6])#列表中是要填充的数值,按行
array([[4, 5, 6],
       [4, 5, 6]])
#随机矩阵np.random()
np.random.rand(3) #生成服从0-1均匀分布的三个随机数
array([0.69693795, 0.77524397, 0.84901272])
np.random.rand(3,3) #生成服从0-1均匀分布的三行三列的随机数
array([[0.31053969, 0.01425395, 0.49375968],
       [0.35167381, 0.33864666, 0.36161546],
       [0.19646831, 0.7157192 , 0.61992155]])
#生成a到b上的均匀分布的随机数
a,b = 5,15
(b-a)*np.random.rand(3)+a
array([ 9.83526578, 14.11106503, 12.64892721])
#生成0到1的服从标准正态分布的随机数
np.random.randn(3)
array([-0.62224203,  0.61740145,  0.41347703])
np.random.randn(2,2)
array([[ 1.61607207,  0.64803234],
       [-0.16899488, -1.11458885]])
sigma,mu = 2.5,3
mu+np.random.randn(3)*sigma
array([4.8267152 , 6.0578538 , 3.40683054])
#可以生成随机整数的最小值最大值和维度大小
low,high,size = 5,15,(2,3)
np.random.randint(low,high,size)

array([[12,  8, 10],
       [12, 13, 12]])
#choice
my_list = ['a','b','c','d']
np.random.choice(my_list,2,replace=False,p = [0.1,0.7,0.1,0.1])

array(['b', 'c'], dtype='<U1')
np.random.choice(my_list,(3,3))

array([['a', 'd', 'd'],
       ['c', 'b', 'b'],
       ['a', 'a', 'a']], dtype='<U1')
np.random.permutation(my_list)
array(['a', 'c', 'b', 'd'], dtype='<U1')

数组的变形与组合

#转置
np.zeros((2,3)).T
array([[0., 0.],
       [0., 0.],
       [0., 0.]])
#合并
np.r_[np.zeros((2,3)),np.zeros((2,3))] #r_是上下 row行
array([[0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.]])
np.c_[np.zeros((2,3)),np.zeros((2,3))] #c_是左右 column列
array([[0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0.]])
np.r_[np.array([0,0]),np.zeros((2,1))]
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-36-911ceccd7020> in <module>
----> 1 np.r_[np.array([0,0]),np.zeros((2,1))]


D:\anaconda\lib\site-packages\numpy\lib\index_tricks.py in __getitem__(self, key)
    402                 objs[k] = objs[k].astype(final_dtype)
    403 
--> 404         res = self.concatenate(tuple(objs), axis=axis)
    405 
    406         if matrix:


ValueError: all the input arrays must have same number of dimensions
np.c_[np.array([0,0]),np.zeros((2,1))]
array([[0., 0.],
       [0., 0.]])
#reshape维度变换
target = np.arange(8).reshape(2,4)
target
array([[0, 1, 2, 3],
       [4, 5, 6, 7]])
target.reshape((4,2),order = 'c')
array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7]])
target.reshape((4,2),order = 'f')
array([[0, 2],
       [4, 6],
       [1, 3],
       [5, 7]])
target.reshape((4,-1))
target
array([[0, 1, 2, 3],
       [4, 5, 6, 7]])
target = np.ones((3,1))
target
array([[1.],
       [1.],
       [1.]])
target.reshape(-1)
array([1., 1., 1.])

数组的切片与索引

import numpy as np
target = np.arange(9).reshape(3,3)
target
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
target[:-1,[0,2]]  #取前两行 取1、3列

array([[0, 2],
       [3, 5]])
target[np.ix_([True,False,True],[True,False,True])] #第二行不取 第二列不取
array([[0, 2],
       [6, 8]])
target[np.ix_([1,2],[True,False,True])] #3568
array([[3, 5],
       [6, 8]])
#维度是1维时
new = target.reshape(-1)
new
array([0, 1, 2, 3, 4, 5, 6, 7, 8])
new[new%2==0]
array([0, 2, 4, 6, 8])

常用函数

#where 是一种条件函数 指定满足条件与不满足条件对应位置的填充值
a = np.array([-1,1,-1,0])
np.where(a>0,a,5) #if else
array([5, 1, 5, 5])
#索引
a = np.array([-2,-5,0,1,3,-1])
np.nonzero(a)
(array([0, 1, 3, 4, 5], dtype=int64),)
a.argmax()
4
a.argmin()
1
# any all
a = np.array([0,1])
a.any()
True
a.all()
False
#cumprod cumsum diff
a = np.array([1,5,8])
a.cumprod()

array([ 1,  5, 40], dtype=int32)
a.cumsum()
array([ 1,  6, 14], dtype=int32)
np.diff(a)
array([4, 3])
#统计函数
#最大最小平均数中位数方差标准差求和分位数相关系数协方差 比较简单


广播机制

res = 3 * np.ones((2,2)) + 1
res
import numpy as np
res = 3*np.ones((2,2))+1
res
array([[4., 4.],
       [4., 4.]])
np.ones((2,2))
array([[1., 1.],
       [1., 1.]])
res = 1/res
res
array([[0.25, 0.25],
       [0.25, 0.25]])
import numpy as np
res = np.ones((3,2))
res
array([[1., 1.],
       [1., 1.],
       [1., 1.]])
res*np.array([[2,3]])
array([[2., 3.],
       [2., 3.],
       [2., 3.]])
res*np.array([[2],[3],[4]])

array([[2., 2.],
       [3., 3.],
       [4., 4.]])
res*np.array([[2]])
array([[2., 2.],
       [2., 2.],
       [2., 2.]])

向量与矩阵的运算

#向量内积
a = np.array([1,2,3])
b = np.array([1,3,5])
a.dot(b) #1+6+15=22
22
#向量范数和矩阵范数
martix_target = np.arange(4).reshape(-1,2)
martix_target
array([[0, 1],
       [2, 3]])
np.arange(4)
array([0, 1, 2, 3])
np.arange(4).reshape(-1,2)
array([[0, 1],
       [2, 3]])
np.linalg.norm(martix_target,'fro')

3.7416573867739413
np.linalg.norm(martix_target,np.inf)
5.0
#矩阵乘法
a = np.arange(4).reshape(-1,2)
a
array([[0, 1],
       [2, 3]])
b = np.arange(-4,0).reshape(-1,2)
b
array([[-4, -3],
       [-2, -1]])
a@b
array([[ -2,  -1],
       [-14,  -9]])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值