Python Numpy 等差数列arange 向量化运算 四则 函数 比较 矩阵 最值

生成等差数列

numpy.arange(start, end, step)

例1:

r = range(1,10,2)

for i in r:

    print (i)

>>>1 3 5 7 9

(range需要for循环输出,不方便,且不能用于小数)

生成小数等差数列

例2:

import numpy

numpy.arange(0.1,0.5,0.01)

>>>array([0.1 , 0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.2 ,

       0.21, 0.22, 0.23, 0.24, 0.25, 0.26, 0.27, 0.28, 0.29, 0.3 , 0.31,

       0.32, 0.33, 0.34, 0.35, 0.36, 0.37, 0.38, 0.39, 0.4 , 0.41, 0.42,

       0.43, 0.44, 0.45, 0.46, 0.47, 0.48, 0.49])


向量化运算

四则运算

长短一致:

r + r

r - r

r * r

r / r

运算时相同位置进行运算

长短不一致:

r + 1

运算时,将短的重复自身补齐到和长的长度一致后再进行相同位置运算


函数式

numpy.power(r, 5)


比较运算

>>>r>0.3

array([False, False, True.....])

#结合过滤进行使用

>>>r[r>0.3]

只输出结果为True的值


 矩阵转置

>>>numpy.mat(r).T

matrix([[1],

        [3],

        [5],

        [7],

        [9]])


>>>from pandas import DataFrame
        df = DataFrame({
            'col1': numpy.random.randn(5),
            'col2': numpy.random.randn(5)

        })

>>>df

  col1 col2
0 1.392194 -0.186803
1 -1.048910 0.935710
2 1.457584 -0.623617
3 -0.889374 1.605424
4 -0.749914 -0.275273

列的最小值

>>>df.apply(lambda x: min(x)

col1   -1.048910

col2   -0.623617

 
  

dtype: float64

行的最小值

>>>df.apply(lambda x: min(x), axis=1)

0   -0.186803

1   -1.048910

2   -0.623617

3   -0.889374

4   -0.749914

dtype: float64


每行的值是否都大于0

>>>df.apply(lambda x: numpy.all(x>0))

col1    False

col2    False

dtype: bool


每列的值是否都大于0

>>>df.apply(lambda x: numpy.all(x>0),axis=1)

0    False

1    False

2    False

3    False

4    False

dtype: bool


#结合过滤

>>>df[df.apply(lambda x: numpy.all(x>0),axis=1)]

猜你喜欢

转载自blog.csdn.net/weixin_41471128/article/details/80435141
今日推荐