Numpy的一些基本操作
1、使用Numpy打开文件:
import numpy
txt = numpy.genfromtxt("数据统计.txt", delimiter=",", dtype=str)
delimiter表示元素之间通过","分隔,dtype表示默认使用的读取方式,通常默认为使用str值读进来。
2、Numpy最核心的结构——numpy.array()
vector = numpy.array([5, 10, 15, 20])
print(vector)
得到一个一维数据,如下结果:
[ 5 10 15 20]
如果希望得到一个二维数据,可以将二维数据传入numpy.array()
matrix = numpy.array([[5, 10, 15], [20, 25, 30], [35, 40, 45]])
print(matrix)
得到的结果如下:
[[ 5 10 15]
[20 25 30]
[35 40 45]]
这里需要注意的是,numpy.array()中所有的数据都需要用中括号括起来(二维数据需要使用2个中括号),不然的话会报错。
3、shape方法
使用shape方法可以了解当前array的结构情况,即行和列的情况。
vector = numpy.array([1, 2, 3, 4])
print(vector.shape)
#得到结果如下:
(4,)
表示:数据是一维的,共有4个元素。
matrix = numpy.array([[5, 10, 15], [20, 25, 30], [35, 40, 45]])
print(matrix.shape)
#得到结果如下:
(3, 3)
表示:矩阵有3行,3列。
4、dtype方法
numbers = numpy.array([1, 2, 3, 4])
print(numbers.dtype)
# 运行结果:
int32
需要注意的是,使用numpy.array()传入数据的时候,数据类型必须统一
numbers = numpy.array([1, 2, 3, 4.0])
print(numbers)
print(numbers.dtype)
#运行结果:
[1. 2. 3. 4.]
float64
可以发现,将numbers中的4改为4.0后,打印出的结果都由int变成 了float形式,dtype类型也由int32变成了float64。
numbers = numpy.array([1, 2, 3, '4'])
print(numbers)
print(numbers.dtype)
#运行结果:
['1' '2' '3' '4']
<U11
同样,元素的类型都变成了字符串。