数据分析numpy作业03_2020082422

练习1:

在讲解 Matplotlib 的时候,我们使用以下代码绘制分组条形图。
其中讲解到,三根柱子的位置需要同时往左或往右移动时,需要使用到列表推导式。
实际上,duck不必,请使用numpy的所学来优化我们该部分代码。

import matplotlib.pyplot as plt
import numpy as np

#初始化字体
def init_font():
    plt.rcParams['font.sans-serif'] = ['SimHei'] # 步骤一(替换sans-serif字体)
    plt.rcParams['axes.unicode_minus'] = False   # 步骤二(解决坐标轴负数的负号显示问题)


#根据x_po和y_po设置标签位置
def auto_label(x_po:list,y_po:list):
    for x_i,y_i in zip(x_po,y_po):
        plt.annotate(f"{(y_i)}",xy=(x_i,y_i),xytext=(x_i,y_i+50))

#绘制柱形图
def draw_column_chart(fruits:list,Q1_sales:list,Q2_sales:list,width:int):
    #po_l = [i-width/2 for i in list(range(len(fruits)))]
    po_l = np.arange(len(fruits))-width/2  #用numpy进行改进
    print('po_l=',po_l,'len(fruits)=',len(fruits))

    plt.bar(po_l,Q1_sales,width,label="Q1")

    #po_r = [i+width/2 for i in list(range(len(fruits)))]
    po_r = np.arange(len(fruits))+width/2 #用numpy进行改进
    print('po_r=',po_r)
    plt.bar(po_r,Q2_sales,width,label="Q2")

    # 设置图例
    plt.legend()

    # 数据标签
    auto_label(po_l,Q1_sales)
    auto_label(po_r,Q2_sales)

    plt.xticks(list(range(len(fruits))),fruits)

    plt.show()

if __name__ == '__main__':
    init_font()
    fruits = ["苹果", "梨子", "车厘子"]
    Q1_sales = [1000, 800, 3000]
    Q2_sales = [1200, 700, 2800]

    draw_column_chart(fruits, Q1_sales, Q2_sales,0.35)

绘制结果如下图:
在这里插入图片描述

练习2

请完成以下基础练习:
• np.arange(16).reshape(4,4)与2做减法
• np.arange(16).reshape(4,4)与np.arange(16,32).reshape(4,4)做加法运算
• np.arange(8).reshape(2,4)与np.arange(4)运算吗?
• np.arange(8).reshape(2,4)与np.arange(4).reshape(1,4)运算吗?
• np.arange(8).reshape(2,4)与np.arange(4).reshape(4,1)运算吗?

import numpy as np

if __name__ == '__main__':

    #np.arange(16).reshape(4,4)与2做减法
    arr1 = np.arange(16).reshape(4,4)
    print(arr1)
    '''
    [[ 0  1  2  3]
     [ 4  5  6  7]
     [ 8  9 10 11]
     [12 13 14 15]]
    '''
    print(arr1-2)
    '''
    [[-2 -1  0  1]
     [ 2  3  4  5]
     [ 6  7  8  9]
     [10 11 12 13]]
    '''

    #np.arange(16).reshape(4,4)与np.arange(16,32).reshape(4,4)做加法运算
    arr2_01 = np.arange(16).reshape(4,4)
    arr2_02 = np.arange(16,32).reshape(4,4)
    print(arr2_01 + arr2_02)
    '''
    [[16 18 20 22]
     [24 26 28 30]
     [32 34 36 38]
     [40 42 44 46]]
    '''


    #np.arange(8).reshape(2,4)与np.arange(4)运算吗?
    # 可以运算,因为与列数相同并且只有1行的数组之间进行运算,按行广播
    arr3_01 = np.arange(8).reshape(2,4)
    arr3_02 = np.arange(4)
    print('arr3_01=',arr3_01,'arr3_02=',arr3_02)
    '''
    arr3_01=[[0 1 2 3]
             [4 5 6 7]] 
    arr3_02= [0 1 2 3]
    '''
    print(arr3_01-arr3_02)
    '''
    [[0 0 0 0]
     [4 4 4 4]]
    '''

    # np.arange(8).reshape(2,4)与np.arange(4).reshape(1,4)运算吗?
    # 道理同上
    arr4_01 = np.arange(8).reshape(2, 4)
    arr4_02 = np.arange(4).reshape(1,4)
    print(arr4_01 - arr4_02)
    '''
    [[0 0 0 0]
     [4 4 4 4]]
    '''

    #np.arange(8).reshape(2,4)与np.arange(4).reshape(4,1)运算吗?
    # 不能运算,两个运算的arr行列均不相关,无法进行广播
    arr5_01 = np.arange(8).reshape(2,4)
    arr5_02 = np.arange(4).reshape(4,1)
    
    # print(arr5_01-arr5_02) #ValueError: operands could not be broadcast together with shapes (2,4) (4,1)

练习3

请完成以下基础练习:
• 构建数组: np.arange(16).reshape(4,4)
• 选择 第3列
• 选择 1-3 列
• 选择 2,4 列
• 选择 4,7 两个点 将值改为 0
• 过滤出 <5 的值


import numpy as np

'''
练习3
请完成以下基础练习:
• 构建数组: np.arange(16).reshape(4,4)
• 选择 第3列
• 选择 1-3 列
• 选择 2,4 列
• 选择 4,7 两个点 将值改为 0
• 过滤出 <5 的值
'''
if __name__ == '__main__':
    #构建数组: np.arange(16).reshape(4,4)
    arr = np.arange(16).reshape(4,4)
    print('arr=',arr)
    '''
    arr= [[ 0  1  2  3]
             [ 4  5  6  7]
             [ 8  9 10 11]
             [12 13 14 15]]
    '''
    # 选择 第3列
    arr_c3 = arr[:,2]
    print('arr_c3 = ',arr_c3)
    '''
    arr_c3 =  [ 2  6 10 14]
    '''
    # 选择 1-3 列
    arr_c1toc3 = arr[:,(0,1,2)]
    print('arr_c1toc3=',arr_c1toc3)
    '''
     [[ 0  1  2]
     [ 4  5  6]
     [ 8  9 10]
     [12 13 14]]
    '''
    #print(arr[:,0:3])

	#选择 2,4 列
    arr_c2_c4 = arr[:, (1, 3)]
    print('arr_c2_c4 = ',arr_c2_c4)
    '''
    arr_c2_c4 =  [[ 1  3]
                 [ 5  7]
                 [ 9 11]
                 [13 15]]
    '''
    # 选择 4,7 两个点 将值改为 0
    print(arr[(1,1), (0, 3)]) # [4 7]
    arr[1,0] = 0
    arr[1,3] = 0
    print ( arr[(1, 1), (0, 3)] ) #[0 0]
	# 过滤出 <5 的值
    arr = np.arange ( 16 ).reshape ( 4, 4 )
    print ( 'arr=', arr )
    """
    arr= [[ 0  1  2  3]
     [ 4  5  6  7]
     [ 8  9 10 11]
     [12 13 14 15]]
    """
    print ( 'arr 小于5的值=',arr[arr <5] ) #arr 小于5的值= [0 1 2 3 4]

练习4

通过以下代码读取scores.csv 数据
在这里插入图片描述

并且完成以下练习:
• 筛选出 成绩 大于60 并且 小于80 的数据
• 筛选出 成绩 大于80 并且 小于90 的数据
• 筛选出 成绩 大于90 的数据

#方式一:用csv进行读写操作
import csv
import numpy as np

#利用csv模块:读文件并把内容返回为二维码列表中
def read_csvfile_csvM(filename):
    lists_data = []
    with open(filename,'r',encoding='gbk') as f_r:
        data_iterator = csv.reader(f_r)
        for data in data_iterator:
            #print(data)
            #print(type(data))# class 'list'
            lists_data.append(data)
        return lists_data

# 打印numpy.ndarray信息
def print_arr_details(msg:str,arr:np.ndarray):
    print(msg,':','ndim=',arr.ndim,'shape=',arr.shape,'vaule=',arr)

if __name__ == '__main__':
    # 方式一:csv模块读取到二阶list中
    lists_data  = read_csvfile_csvM ( 'scores.csv' )
    #print(lists_data)
    '''
        [['期中', '期末'], ['52', '83'], ['27', '73'], ['14', '42'], ['82', '34'], ['93', '52'], ['89', '90'], ['62', '49'], ['23', '12'], ['98', '0'], ['88', '26'], ['73', '8'], ['67', '29'], ['87', '26'], ['65', '48'], ['99', '38'], ['23', '80'], ['41', '50'], ['38', '12'], ['30', '79'], ['57', '69'], ['12', '41'], ['81', '6'], ['96', '21'], ['58', '72'], ['43', '73'], ['52', '13'], ['36', '33'], ['48', '93'], ['19', '46'], ['25', '77'], ['10', '29'], ['20', '71'], ['74', '77'], ['37', '44'], ['30', '36'], ['22', '48'], ['22', '67'], ['96', '54'], ['38', '53'], ['95', '13']]
    score_data : ndim= 2 shape= (40, 2) vaule= [[52. 83.]
    '''
    # 方式二:用np读取到二维arr中
    # float64
    #score_data = np.loadtxt ( "scores.csv", delimiter=",", skiprows=1)
    #print(score_data.dtype) #float64
    # print_arr_details('score_data',score_data)
    '''
         score_data : ndim= 2 shape= (40, 2) vaule= [[52. 83.]
         [27. 73.]
         [14. 42.]
         [82. 34.]
         [93. 52.]
         ...
         [22. 48.]
         [22. 67.]
         [96. 54.]
         [38. 53.]
         [95. 13.]]
    '''
    # 为保证与scores.csv文件数据一致,指定arr元素为int
    score_data = np.loadtxt ( "scores.csv", delimiter=",", skiprows=1, dtype='int' )

    # 筛选出 成绩 大于60 并且 小于80 的数据
    score_arr001 = score_data[(score_data>60)&(score_data<80)]
    print('score_arr001 = ',score_arr001)
    '''
        score_arr001 =  [73 62 73 67 65 79 69 72 73 77 71 74 77 67]
    '''
    # 筛选出 成绩 大于80 并且 小于90 的数据
    score_arr002 = score_data[(score_data > 80) & (score_data < 90)]
    print ( 'score_arr002 = ', score_arr002 )
    '''
    score_arr002 =  [83 82 89 88 87 81]
    '''
    # 筛选出 成绩 大于90 的数据
    score_arr003 = score_data[score_data > 90]
    print ( 'score_arr003 = ', score_arr003 )
    '''
    score_arr003 =  [93 98 99 96 93 96 95]
    '''

猜你喜欢

转载自blog.csdn.net/Narutolxy/article/details/108200289
今日推荐