numpy模块的使用(二)

ndarry缺失值填充均值:

import numpy as np

def fill_ndarry(t1):

    for i in range(t1.shape[1]):
        temp_col = t1[:,i] # 当前的一列
        nan_num = np.count_nonzero(temp_col!=temp_col)

        if nan_num!=0: # 不为0说明这一列中有nan
            # 当前一列不为nan的array
            temp_not_nan_col = temp_col[temp_col==temp_col] 
            # 把当前为nan的位置替换为不为nan的均值
            temp_col[np.isnan(temp_col)] = temp_not_nan_col.mean()

    return t1
        
    
if __name__=="__main__":
    # 创建二维数组
    t1 = np.arange(12).reshape(3,4).astype(float)   
    # 将某些位置的值设置为nan
    t1[1,2:] = np.nan
    # 输出t1数组
    print(t1)
    print("-"*10)
    # 调用均值函数
    t1 = fill_ndarry(t1)    
    print(t1)

例题:

  • 现在这里有一个英国和美国各自youtube1000多个视频的点击,喜欢,不喜欢,评论数量([“views”,“likes”,“dislikes”,“comment_total”])的csv,运用所学知识,尝试来对其进行操作

  • 数据来源:https://www.kaggle.com/datasnaek/youtube/data

  1. 英国和美国各自youtube1000的数据结合之前的matplotlib绘制出各自的评论数量的直方图
  2. 希望了解英国的youtube中视频的评论数和喜欢数的关系,应该如何绘制改图

1.代码:

import numpy as np
from matplotlib import pyplot as plt

us_file_path = "./youtube_video_data/US_video_data_numbers.csv"
uk_file_path = "./youtube_video_data/GB_video_data_numbers.csv"
# 读取数据
t = np.loadtxt(us_file_path,delimiter=",",dtype="int")

# 取评论数
t_comments = t[:,-1]

# 选择比5000小的数据
t_comments = t_comments[t_comments<5000]

# 组距
d = 50

# 组数
bin_num = (t_comments.max()-t_comments.min())//d

# 设置图片大小
plt.figure(figsize=(20,8),dpi=80)

# 画直方图
plt.hist(t_comments,bin_num)

# 网格
plt.grid()

# 显示图片
plt.show()

效果图:

在这里插入图片描述

2.代码:

import numpy as np
from matplotlib import pyplot as plt
import matplotlib

font = {
    
    'family' : 'WenQuanYi Micro Hei',
        'weight' : 'bold',                
        'size'   : '10'}        

matplotlib.rc("font",**font)

us_file_path = "./youtube_video_data/US_video_data_numbers.csv"
uk_file_path = "./youtube_video_data/GB_video_data_numbers.csv"
# 读取数据
t_uk = np.loadtxt(uk_file_path,delimiter=",",dtype="int")

# 提取喜欢数小于25000的行
t_uk = t_uk[t_uk[:,1]<50000]

# 评论数
t_uk_comments = t_uk[:,-1]
# 喜欢数
t_uk_like = t_uk[:,1]

# 设置图片大小
plt.figure(figsize=(20,8),dpi=80)

# 绘制散点图
plt.scatter(t_uk_like,t_uk_comments)

# 添加描述
plt.xlabel("喜欢数")
plt.ylabel("评论数")
plt.title("评论数和喜欢数的关系")

# 显示
plt.show()

效果图:

在这里插入图片描述

数组的拼接:

In [3]: t1 = np.arange(12).reshape((2,6))

In [4]: t1
Out[4]: 
array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11]])

In [5]: t2 = np.arange(12,24).reshape(2,6)

In [6]: t2
Out[6]: 
array([[12, 13, 14, 15, 16, 17],
       [18, 19, 20, 21, 22, 23]])

In [7]: np.vstack((t1,t2))   ————> 垂直拼接
Out[7]: 
array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17],
       [18, 19, 20, 21, 22, 23]])

In [8]: np.hstack((t1,t2))  ————> 水平拼接
Out[8]: 
array([[ 0,  1,  2,  3,  4,  5, 12, 13, 14, 15, 16, 17],
       [ 6,  7,  8,  9, 10, 11, 18, 19, 20, 21, 22, 23]])

数组的行列交换:

In [9]: t = np.arange(12,24).reshape(3,4)

In [10]: t
Out[10]: 
array([[12, 13, 14, 15],
       [16, 17, 18, 19],
       [20, 21, 22, 23]])

In [11]: t[[1,2],:] = t [[2,1],:]  ——>行交换(第2,3行交换)

In [12]: t
Out[12]: 
array([[12, 13, 14, 15],
       [20, 21, 22, 23],
       [16, 17, 18, 19]])

In [13]: t[:,[0,2]] = t[:,[2,0]]   ——>列交换(第1,3列交换)

In [14]: t
Out[14]: 
array([[14, 13, 12, 15],
       [22, 21, 20, 23],
       [18, 17, 16, 19]])

例:

  • 现在希望把之前案例中两个国家的数据方法一起来研究分析,同时保留国家的信息(每条数据的国家来源),应该怎么办

代码:

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"

# 读取数据
us_data = np.loadtxt(us_file_path,delimiter=",",dtype="int")
uk_data = np.loadtxt(uk_file_path,delimiter=",",dtype="int")


# 添加国家信息
# 构造全为0的数据
zeros_data = np.zeros((us_data.shape[0],1)).astype(int)
ones_data = np.ones((uk_data.shape[0],1)).astype(int)

# 分别添加一列全为0或1的数组
us_data = np.hstack((us_data,zeros_data))
uk_data = np.hstack((uk_data,ones_data))

# print(uk_data)
# 拼接数据
finally_data = np.vstack((us_data,uk_data))

print(finally_data)

numpy更多好用的方法:

1. 获取最大值最小值的位置
   1) np.argmax(t,axis=0) <<==>> t.argmax(axis=0)
   2) np.argmin(t,axis=1)
3. 创建一个全0的数组: np.zeros((3,4))
4. 创建一个全1的数组:np.ones((3,4))
5. 创建一个对角线为1的正方形数组(方阵):np.eye(3)

numpy生成随机数:

  • 随机数方法都在np.random下,如: np.random.rand(2,3)

在这里插入图片描述

分布的补充:

均匀分布:

  在相同的大小范围内的出现概率是等可能的

正态分布:

  呈钟型,两头低,中间高,左右对称

numpy的注意点copy和view:

a = b 完全不复制,a和b相互影响
a = b[:],视图的操作,一种切片,会创建新的对象a,但是a的数据完全由b保管,他们两个的数据变化是一致的
a = b.copy(),复制,a和b互不影响

猜你喜欢

转载自blog.csdn.net/qq_46456049/article/details/108912302