Python学习之Numpy基础(一)

一:先安装所需要的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.csdn.net/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]

注意:可以用":"表示取'所有的'的意思



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值