Python - Numpy - 01 - 安装 - 数组

查看更多资源

1. 安装 anaconda :

https://baijiahao.baidu.com/s?id=1616120886763657106&wfr=spider&for=pc

2. vscode 中使用 anaconda :

https://cloud.tencent.com/developer/news/313349

3. 读取txt中的数据 :

import numpy

# 以“,”为分隔符,str类型
world_alcohol = numpy.genfromtxt(
    'C:/Users/ygbx/Desktop/python/numpy/world_alcohol.txt', delimiter=",", dtype=str)

print(type(world_alcohol))
# <class 'numpy.ndarray'>

print(world_alcohol)
# [['Year' 'who region' 'country' 'beverage types' 'display value']
#  ['1991' 'xiao yang1' 'beijing1' 'wine' '1']]

print(world_alcohol[0, 1])  # who region  取值

# 查看 函数的信息
print(help(numpy.genfromtxt))
# world_alcohol.txt 中的原始数据

Year,who region,country,beverage types,display value
1991,xiao yang1,beijing1,wine,1

 4. 创建多维数组:

import numpy

# arr1 = numpy.array([1, 2, 3])
# arr2 = numpy.array([[1, 2, 3], [4, 5, 6]])

# print(arr1)
# print(arr2)
# print(arr1.shape)  # (3,)
# print(arr2.shape)  # (2,3) 数组形状  二行三列


# arr3 = numpy.array([1, 2, 3])
# print(arr3.dtype)  # int32 数据类型

# arr4 = numpy.array([1, 2, 3.0])
# print(arr4.dtype)  # float64 [1.,2.,3.] 如果数据类型不一致,会自动转换一致

5. 多维数组取值 : 

arr8 = numpy.array([1, 2, 3, 4, 3, 6])
r8 = (arr8 == 3) # arr8 中等于3 的值
print(r8)  # [False False  True False True False]
print(arr8[r8])  # [3,3] 返回 相等的值

arr9 = numpy.array([
    [1, 2, 3],
    [4, 1, 6]
])
r9 = (arr9 == 1)
print(r9)  # [1,1]
# [[ True False False]
#  [False True False]]
print(arr9[r9])
arr10 = numpy.array([
    [1, 2, 3],
    [3, 2, 1],
    [2, 1, 3]
])
r10 = (arr10[:, 1] == 2) # 每行的第二列值 是否等于2
print(r10)  # [ True  True False]

print(arr10[r10, :]) # 获取 每行的第二列值等于2 的数据
# [[1 2 3]
#  [3 2 1]]
arr11 = numpy.array([1, 2, 3, 4, 5])
r11_and = (arr11 == 1) & (arr11 == 2) # arr11 的值等于1 且 等于2
print(r11_and)  # [False False False False False]

r11_or = (arr11 == 1) | (arr11 == 2) # arr11 的值等于1 或 等于2
print(r11_or)  # [ True  True False False False]
# 找出 多维数组中 第二列的数据等于2的数据,并且从结果中找出等于1的值
arr12 = numpy.array([
    [1, 2, 3],
    [2, 2, 1],
    [3, 1, 2]
])
r12_col = arr12[:, 1] == 2 # arr12中每行第二列的数据 是否等于2
print(r12_col)  # [ True  True False]

r12_row = arr12[r12_col] == 1 # arr12中每行第二列的数据等于2的 行中值是否等于1
print(r12_row)
# [[ True False False]
#  [False False  True]]

6. 修改类型、求最值、求和 : 

arr13 = numpy.array([1, 2, 3])
print(arr13.dtype)  # int32 数据类型

arr13_str = arr13.astype(float) # 修改 数据类型为float
print(arr13_str)  # [1. 2. 3.]

arr14 = numpy.array([1, 2, 4]) # 求最大、最小值
print(arr14.min())  # 1
print(arr14.max())  # 4
# print(help(numpy.array))

arr15 = numpy.array([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
])
print(arr15.sum())  # 45 所有数据之和
print(arr15.sum(axis=1))  # [ 6 15 24] 每行数据之和
print(arr15.sum(axis=0))  # [12 15 18] 每列数据之和

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值