Python通用函数实现数组计算的方法

yipeiwu_com6年前Python基础

一.数组的运算

数组的运算可以进行加减乘除,同时也可以将这些算数运算符进行任意的组合已达到效果。

>>> x=np.arange(5)
>>> x
array([0, 1, 2, 3, 4])
>>> x=5
>>> x=np.arange(5)
>>> x+5
array([5, 6, 7, 8, 9])
>>> x-5
array([-5, -4, -3, -2, -1])
>>> x*2
array([0, 2, 4, 6, 8])
>>> x/2
array([0. , 0.5, 1. , 1.5, 2. ])
>>> x//2
array([0, 0, 1, 1, 2], dtype=int32)

二.绝对值的运算

一共有三种方法,第一种方法是直接利用不是NumPy库的abs函数进行计算,第二种和第三种方法则是利用numpy库的abs函数和absolute函数进行运算。如下所示:

>>> x=np.array([1,2,3,-4,-5,-6])
>>> x
array([ 1, 2, 3, -4, -5, -6])
>>> abs(x)
array([1, 2, 3, 4, 5, 6])
>>> np.abs(x)
array([1, 2, 3, 4, 5, 6])
>>> np.absolute(x)
array([1, 2, 3, 4, 5, 6])

三.三角函数的运算

首先定义一个a的np当中的array对象,然后再进行运算:

>>> a
array([0.    , 1.57079633, 3.14159265])
>>> np.sin(a)
array([0.0000000e+00, 1.0000000e+00, 1.2246468e-16])
>>> np.cos(a)
array([ 1.000000e+00, 6.123234e-17, -1.000000e+00])
>>> np.tan(a)
array([ 0.00000000e+00, 1.63312394e+16, -1.22464680e-16])

四.指数和对数的运算

指数的运算:

>>> x=[1,2,3]
>>> x
[1, 2, 3]
>>> np.exp(x)
array([ 2.71828183, 7.3890561 , 20.08553692])
>>> np.exp2(x)
array([2., 4., 8.])

np.power(3,x)
array([ 3, 9, 27], dtype=int32)

对数的运算:

>>> np.log(x)
array([0.    , 0.69314718, 1.09861229])
>>> np.log2(x)
array([0.    , 1.    , 1.5849625])
>>> x
[1, 2, 3]
>>> np.log10(x)
array([0.    , 0.30103  , 0.47712125])

总结

以上所述是小编给大家介绍的Python通用函数实现数组计算的方法,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!

相关文章

Python 类方法和实例方法(@classmethod),静态方法(@staticmethod)原理与用法分析

Python 类方法和实例方法(@classmethod),静态方法(@staticmethod)原理与用法分析

本文实例讲述了Python 类方法和实例方法(@classmethod),静态方法(@staticmethod)。分享给大家供大家参考,具体如下: demo.py(类方法,@classm...

详解pyppeteer(python版puppeteer)基本使用

详解pyppeteer(python版puppeteer)基本使用

一、前言 以前使用selenium的无头浏览器,自从phantomjs2016后慢慢不更新了之后,selenium也开始找下家,这时候谷歌的chrome率先搞出来无头浏览器并开放了各种a...

Python编程argparse入门浅析

Python编程argparse入门浅析

本文研究的主要是Python编程argparse的相关内容,具体介绍如下。 #aaa.py #version 3.5 import os #这句是没用了,不知道为什么markd...

Python Pandas 转换unix时间戳方式

Python Pandas 转换unix时间戳方式

使用pandas自带的pd.to_datetime把 unix 时间戳转为时间时默认是转换为 GMT标准时间   北京时间比这个时间还要加 8个小时, 使用pyth...

详解Python 数据库 (sqlite3)应用

详解Python 数据库 (sqlite3)应用

Python自带一个轻量级的关系型数据库SQLite。这一数据库使用SQL语言。SQLite作为后端数据库,可以搭配Python建网站,或者制作有数据存储需求的工具。SQLite还在其它...