numpy(创建数组、对数组进行操作)

numpy创建一个数组:

import numpy as np

t1 = np.array([1,2,3])
print(t1)
print(type(t1))

t2 = np.array(range(10))
print(t2)
print(type(t2))

t3 = np.arange(10)
print(t3)
print(type(t3))

输出:

F:\Softwares\Anaconda\python.exe F:/PycharmProjects/HMdatesys/matplotlib/numpy创建数组.py
[1 2 3]
<class 'numpy.ndarray'>

numpy.ndarray为numpy创建的数组类型

import random
import numpy as np

#使用numpy生成数组,得到numpy.ndarray的数据类型
t1 = np.array([1,2,3])
print(t1)
print(type(t1))

t2 = np.array(range(10))
print(t2)
print(type(t2))
print(t2.dtype)

t3 = np.arange(10)
print(t3)
print(type(t3))
print(t3.dtype)

print('***********************'*5)

#dtype可以设定numpy中的数据类型
t4 = np.arange(2,10,2,dtype='float32')
print(t4)
print(type(t4))
print(t4.dtype)

#调整数据类型

t5 = t4.astype('int8')
print(t5)
print(t5.dtype)


#numpy中的小数
t6 = np.array([random.random() for i in range(10)])
print(t6)
print(t6.dtype)
#取2位小数
t7 = np.round(t6,2)
print(t7)

numpy数组计算

import numpy as np

'''
#t为数组和数进行计算
t1 = np.array([[1,2,3],[4,5,6]])
print(t1)
print(t1.dtype)

#加减法,对数组中所有的数进行加减操作
t2=t1+2
print(t2)
print(t2.dtype)

t3=t1-3
print(t3)
print(t3.dtype)

#乘除法
t4 = t1*3
print(t4)
print(t4.dtype)
#/0时会返回nan(0/0),inf(数字/0)
t5=t1/0
print(t5)
print(t5.dtype)

t6=t1/2
print(t6)
print(t6.dtype)

'''

#a,b为数组和数进行计算
#无论什么计算,当两个数组形状匹配时,对应位置计算;
#      当两个数组形状不匹配(行、列均不能匹配)时,大的对小的依次计算

a = np.array([[1,2,3],[4,5,6]])
b = np.array([[7,8,9],[10,11,12]])
c = np.array([1,2,3])
d = np.array([1,3])
e = np.array([[1],[2]])

c1=a+b
print(c1)
print(c1.dtype)

c2=a+c
print(c2)
print(c2.dtype)

c3=a*b
print(c3)
print(c3.dtype)

c4=a*c
print(c4)
print(c4.dtype)

c5=c*a
print(c5)
print(c5.dtype)

#若最小单位都不匹配,则报错
#c6=a*d
#print(c6)
#print(c6.dtype)

c7=a*e
print(c7)
print(c7.dtype)

numpy数组的取值

import numpy as np

us_file_path = "./youtube_video_data/US_video_data_numbers.csv"
uk_file_path = "./youtube_video_data/GB_video_data_numbers.csv"

# t1 = np.loadtxt(us_file_path,delimiter=",",dtype="int",unpack=True)
t2 = np.loadtxt(us_file_path,delimiter=",",dtype="int")

# print(t1)
print(t2)

print("*"*100)

#取行
# print(t2[2])

#取连续的多行
# print(t2[2:])

#取不连续的多行;注意方括号的使用
# print(t2[[2,8,10]])

# print(t2[1,:])
# print(t2[2:,:])
# print(t2[[2,10,3],:])

#取列
# print(t2[:,0])

#取连续的多列
# print(t2[:,2:])

#取不连续的多列
# print(t2[:,[0,2]])

#取行和列,取第3行,第四列的值
# a = t2[2,3]
# print(a)
# print(type(a))

#取多行和多列,取第3行到第五行,第2列到第4列的结果
#取的是行和列交叉点的位置
b = t2[2:5,1:4]
# print(b)

#取多个不相邻的点  此处应该注意
#选出来的结果是(0,0) (2,1) (2,3)
c = t2[[0,2,2],[0,1,3]]
print(c)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值