数据统计(python)numpy :数组、数组形状、csv读取、索引、nan和inf、数组填充、bar案例、scatter案例、数组拼接、随机数

本文通过代码示例介绍了使用Python的numpy库进行数据处理的各种操作,包括数组创建、形状调整、CSV文件读取、索引选择、处理NaN和Inf、数组填充、绘制条形图和散点图,以及数组拼接和生成随机数等实用技巧。
摘要由CSDN通过智能技术生成

1.数组_代码示例

import numpy as np
import random

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

#使用array中的range()
t2 = np.array(range(2, 10))
print(type(t2))  # <class 'numpy.ndarray'>
print(t2)  # [1 3 2 5]

t3 = np.arange(1, 10, 2)
print(type(t3))  # <class 'numpy.ndarray'>
print(t3)  # [2 3 4 5 6 7 8 9]

print(t3.dtype) # t3数据类型
print('*'*10)  # int32

#numpy中的数据类型
t4 = np.array(range(1, 4), dtype="i1") # "i1"表示int8
print(t4)  # [1 2 3]
print(t4.dtype)  # int8

##numpy中的bool类型
t5 = np.array([1,1,0,1,0,0],dtype=bool)
print(t5)  # [ True  True False  True False False]
print(t5.dtype)  # bool

#调整数据类型
t6 = t5.astype("int8")
print(t6)  # [1 1 0 1 0 0]
print(t6.dtype)  # int8

#numpy中的小数
t7 = np.array([random.random() for i in range(3)])
print(t7)  # [0.96033818 0.63804794 0.82357959]
print(t7.dtype)  # float64

t8 = np.round(t7, 2)
print(t8)  # [0.96 0.64 0.82]

2.数组形状_代码示例

import numpy as np

a = np.array([[1,2,3], [4,5,6]])
print(a.shape)  # (2, 1)
print(a.reshape(3, 2))  # [[1, 2], [3, 4], [5, 6]]
print(a.reshape(1, 6))  # [[1, 2, 3, 4, 5, 6]]
print(a.flatten())  # [1, 2, 3, 4, 5, 6]  一维数组
print(a+1)  # [[2, 3, 4], [5, 6, 7]]  广播机制
print(a*2)  # [[ 2,  4,  6], [ 8, 10, 12]]

b = np.array([1, 2, 3])
print(a+b)  # [[2, 4, 6], [5, 7, 9]]
print(a*b)  # [[ 1,  4,  9], [ 4, 10, 18]]
print(a-b)  # [[0, 0, 0], [3, 3, 3]]

3.csv读取_代码示例

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"

# delimiter分割字符串, dtype数据类型, unpack是否转置
t1 = np.loadtxt(us_file_path, delimiter=",", dtype="int", unpack
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值