一:先安装所需要的Python库Numpy
import numpy
二:读一个文件
numpy.genfromtxt("绝对路径或相对路径",delimer="分隔符",dtype=以(str/float/..)方式读取数据)
通常先以str方式读入数据,再转为其他类型的数据
world_alcohol = numpy.genfromtxt("world_alcohol.txt", delimer=",", dtype=str)
其中word_alcohol.text中的部分数据为:
Year,WHO region,Country,Beverage Types,Display Value 1986,Western Pacific,Viet Nam,Wine,0 1986,Americas,Uruguay,Other,0.5
三:查看打印结果
#查看当前变量的结构 print(type(world_alcohol)) #查看当前变量 print(world_alcohol)<class 'numpy. ndarray'>
[['Year' 'WHO region' 'Country' 'Beverage Types' 'Display Value']
['1986' 'Western Pacific' 'Viet Nam' 'Wine' '0']
['1986' 'Americas' 'Uruguay' 'Other' '0.5']
...,
['1987' 'Africa' 'Malawi' 'Other' '0.75']
['1989' 'Americas' 'Bahamas' 'Wine' '1.5']
['1985' 'Africa' 'Malawi' 'Spirits' '0.31']]
可将此数据结构视作二位矩阵
四:查看更多用法
print(help(numpy.genfromtxt))
http://blog.youkuaiyun.com/cjgs45/article/details/79516482
五:自定义ndarray数据
一维:
vector = numpy.array([1, 3, 5])
打印结果:
[1 3 5]
二维:
matrix = numpy.array([[1, 3, 5], [2, 4, 6], [10, 30, 50]])
打印结果:
[[ 1 3 5]
[ 2 4 6]
[10 30 50]]
三维:写三个中括号
六:查看ndarray的结构
print(vector.shape) print(matrix.shape)
打印结果:
(3,)
(3, 3)
表示:(几行,几列)
七:注意
numpy.array中传入的值类型要相同,如有一个值得类型不同,则全部值得类型都会变化
'int32'<'float64'<'<U11'
查看类型方法:
print(vector.dtype)
八:取数据
1.取某一个值
uruguay_other_1986 = world_alcohol[2, 4] first_country = world_alcohol[1, 2] print(uruguay_other_1986) print(first_country)打印结果:
0.5
Viet Nam
2.取某几个连续值
vector = numpy.array([10, 20, 30, 40, 50]) print(vector[1:3]) #相当于 (1,3]
打印结果:
[20 30]
3.取某一列
matrix = numpy.array([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]) print(matrix[:, 1])
打印结果:
[2 5 8]
注意:可以用":"表示取'所有的'的意思