numpy是科学计算包(Numeric Python)
关于numpy的命令可以使用help查看,如help(numpy.array)
1.numpy中数据要为相同的数据类型,否则会强制转换
>>> from numpy import *
>>> a = array([1,2,3.0])
>>> print(a)
[1. 2. 3.] #这里的结果就是转换成相同的类型浮点型
>>> from numpy import *
>>> b = array([1,2,'i'])
>>> print(b)
['1' '2' 'i'] #转化成了string类型
2.numpy数据中数据类型的转换numpy.astype()
>>> from numpy import *
>>> vector = array(["1","2"])
>>> vectorF = vector.astype(float)
>>> print(vectorF)
[1. 2.]
3.numpy读数据numpy.genfromtxt()读取文件并转化成矩阵
函数的原始形式:
numpy.genfromtxt(fname, dtype=, comments='#', delimiter=None,
skip_header=0, skip_footer=0, converters=None, missing_values=None,
filling_values=None, usecols=None, names=None, excludelist=None, deletechars=None,
replace_space='_', autostrip=False, case_sensitive=True, defaultfmt='f%i', unpack=None,
usemask=False, loose=True, invalid_raise=True, max_rows=None)[source]
fname:文件名(注意文件的路径)
delimiter:str,int,or sequence,optional.他是分割值,即表示你的数组用什么来分割
dtype:分割后数组的数据类型,默认是根据每行数据数据类型(独立地)
names:列的名称(可重写),dtype的数据类型对应着每一列的数据类型
from numpy import *
f = genfromtxt(fname=r'E:\\奋斗历程\\Machine_Learning\\MLiA_SourceCode\\'
r'machinelearninginaction\\Ch02\\datingTestSet.txt',
delimiter='\t',names=['a','b','c','d'],dtype=['i8','f8','f8','U12'])
print(f[0]) #f的形式是[()()()...],f[0]结果是(40920, 8.326976, 0.953952, 'largeDoses')
4.numpy可以通过布尔值对数组进行索引
from numpy import *
vector = array([[1,2,3,4],[0,9,7,9]])
b = vector != 1
print(b)
print(vector[b])
"""
结果是:
[[False True True True]
[ True True True True]]
[2 3 4 0 9 7 9]
"""
这个性质适合给某个元素进行赋值
from numpy import *
vector = array([[1,2,3,4],[0,9,7,9]])
b = vector == 1
print(b)
print(vector[b])
vector[b] = 6
print(vector)
结果是:
5.用于多个数组的连接numpy.concatenate(x,axis=0)
import numpy as np
x = [[1, 2],
[3, 4]]
x1 = np.concatenate([x, x], axis=0)
print("x1 axis=0")
print(x1)
x2 = np.concatenate([x, x], axis=1)
print("x2 axis=1")
print(x2)
---------------------
本文来自 DreamLee0625 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/vitaminc4/article/details/79332459?utm_source=copy
☆持续更新