python学习_day7---数据分析matplotlib+pandas

一、matplotlib

1、柱状图

x轴数据量少

柱子宽度一致,没什么意义,一般只关注其高度

import numpy as np
import matplotlib.pyplot as plt

# 修改rc参数,支持中文
plt.rcParams["font.sans-serif"] = "SimHei"
# 修改rc参数,支持负号
plt.rcParams['axes.unicode_minus'] = False

data = np.load("../day6/国民经济核算季度数据.npz", allow_pickle=True)
for tmp in data:
    print(tmp)
columns = data["columns"].tolist()  # 转换为列表
info = data["values"]
print(info)
print(columns)
# 2017年第一季度 农林牧渔业、工业....房地产业、其他行业
# 柱状图
ind = columns.index('农林牧渔业增加值_当季值(亿元)')
x_data = columns[ind:]
print('-' * 70)
x_data = [tmp[: tmp.index("业") + 1] for tmp in x_data]
print(x_data)

# y轴数据
y_data = info[0, ind:]
print(y_data)

# 创建画布
plt.figure()

# 柱状图的绘制
plt.bar(x_data, y_data, width=0.5)

plt.xticks(rotation=45)
plt.title("2017年第一季度其他产业生产总值")
plt.xlabel("各个产业")
plt.ylabel("总值")
plt.show()

在这里插入图片描述

2、直方图

查看数据分布,查看落在各个区间的数据量有多少
柱子高度:落在该区间的数据量
柱子宽度:由区间宽度决定,代表区间的范围,有意义

"""
直方图
给定一堆数据
给定一个区间(划分为子区间)
统计数据落在各个子区间的数据量
"""
import numpy as np
import matplotlib.pyplot as plt

# 学生身高直方图----- 学生普遍身高在什么范围
# 1、确定一堆数据
# 指定范围随机小数
data = np.random.uniform(low=140, high=190, size=50)
data = [float("%.2f" % tmp) for tmp in data]
print("身高数据\n", data)

# 2、确定区间信息
# a、区间数目,group=5
# b、自定义区间 (140 155) (155 160)  不需要
# (140, 155, 160, 170, 180, 190)
# 前闭后开 [140, 155) [155,160)...[180,190]

# 绘制 hist
# 参数:数据、区间信息
# plt.hist(data, bins=5, facecolor='b', edgecolor='r')
# plt.hist(data, facecolor='b', edgecolor='r')

# 自定义区间
bin = [140, 155, 160, 170, 180, 190]
plt.hist(data, bins=bin, facecolor='b', edgecolor='r')

# 增加网络线
# 参数b 是否显示 网格线
# axis='y' 垂直于Y轴的网格线
plt.grid(b=True, axis='y', alpha=0.2)
plt.yticks(np.arange(0, 20, 1))
plt.xticks(bin)
plt.show()

在这里插入图片描述

# 创建10000个数据点--服从标准正态的随机数
# 观察 各个子区间的数量
# 利用直方图

# print(np.random.random((3, 4)))  # 0-1之间的随机数
# print(np.random.randn(6))  # 服从标准正态的随机数
# print(np.random.rand(2))  # 服从均匀分布的随机数

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(1)
# data = np.random.randn(1000)
data = np.random.rand(1000)
data = [float("%.2f" % tmp) for tmp in data]

plt.hist(data, bins=5, facecolor='b', edgecolor='r')
# plt.yticks(np.arange(0, 5))
# plt.savefig("正态分布直方图2.jpg")
plt.show()

在这里插入图片描述

3、饼状图

"""
饼状图
数据部分和部分之间的关系,部分和整体的关系
"""
import matplotlib.pyplot as plt

# 修改rc参数,支持中文
plt.rcParams["font.sans-serif"] = "SimHei"
# 修改rc参数,支持负号
plt.rcParams['axes.unicode_minus'] = False
# 准备数据
# 第1产业、第2产业、第3产业
label = ["第1产业", "第2产业", "第3产业"]
data = [10, 20, 30]

# 绘图 pie
# autopct 百分比的显示信息
# explode 各个扇形离圆心的距离
# pctdistance 显示百分比信息的位置,离圆心距离,默认0.6
plt.pie(data,
        labels=label,
        autopct="%.2f%%",
        explode=[0.01, 0.05, 0.03],
        pctdistance=0.9,
        shadow=True)

plt.show()

在这里插入图片描述

4、雷达图

import matplotlib.pyplot as plt
import numpy as np

# 使用范围:如果对某个事物,从多个维度进行描述----高维

# 修改rc参数,支持中文
plt.rcParams["font.sans-serif"] = "SimHei"
# 修改rc参数,支持负号
plt.rcParams['axes.unicode_minus'] = False

# 1、将圆分为5份
angle = np.linspace(0, 2 * np.pi, num=5, endpoint=False).tolist()
print(angle)

data = [2, 3.5, 4, 4.5, 5]
data2 = [3, 4, 2, 1, 3]
lable = ["生存评分", '输出评分', '团战评分', 'KDA', '发育评分']

# 2、数据和角度的闭合
data.append(data[0])
data2.append(data2[0])
print(data)

angle.append(angle[0])
print("新的角度\n", angle)

# 3、绘图
# 传入角度和数据
plt.polar(angle, data)
plt.polar(angle, data2)
plt.legend(["战队1", "战队2"])
plt.show()

在这里插入图片描述

二、pandas

1、DataFrame

1>DataFrame的创建

import pandas as pd

# 一、DataFrame的创建
# 如果没有明确指定行/列索引,默认从0开始
"""
行索引、列索引和数据部分
"""
col = ["name", "age", "group"]
ind = ["stu0", "stu1", 'stu2', 'stu3']
data = [["张三", 19, 1],
        ["李四", 20, 1],
        ["王五", 18, 2],
        ["赵六", 19, 2]]

# ① 逐个传入 行索引、列索引和数据部分
df1 = pd.DataFrame(index=ind, columns=col, data=data)
print("df1\n", df1)
"""
df1
      name  age  group
stu0   张三   19      1
stu1   李四   20      1
stu2   王五   18      2
stu3   赵六   19      2
"""
# ② 以字典的形式创建

# 列名称作为key, 每一列的值为value值
d1 = {
    
    "name": ["张三", "李四", "王五", "赵六"],
      "age": [19, 20, 18, 19],
      "group": [1, 1, 2, 2]}

df2 = pd.DataFrame(data=d1, index=ind)
print("df2\n", df2)
"""
df2
      name  age  group
stu0   张三   19      1
stu1   李四   20      1
stu2   王五   18      2
stu3   赵六   19      2
"""
import numpy as np

data = np.load("../day5/lol_data.npz")
# for tmp in data:
#     print(tmp)  # data columns

info = data["data"]  # ----数据部分
columns = data["columns"]  # -----列索引

df3 = pd.DataFrame(data=info, columns=columns)

# 修改行索引
new_index = ["ind_%d" % tmp for tmp in range(22)]
# print(new_index)

df3.index = new_index

print("df3\n", df3)
"""
df3
             工号   姓名  部分  岗位     薪资  工龄 满意度  状态
ind_0    lol-1  孙悟空  战士  上单  50000  10   3  离职
ind_1   lol-10   光辉  AP  中单  10000   3   2  在职
ind_2   lol-11  石头人  坦克  辅助   5000   3   1  在职
ind_3   lol-12   萝莉  AD  射手  50000   3   3  离职
ind_4   lol-13   提莫  AP  辅助   2500   3   2  在职
ind_5   lol-14   狗头  战士  上单  11000   3   1  在职
ind_6   lol-15  轮子妈  AD  射手  12500   3   1  在职
ind_7   lol-16   冰鸟  AP  辅助  20000   2   2  在职
ind_8   lol-17   牛头  坦克  辅助   8000   2   1  在职
ind_9   lol-18   剑豪  刺客  中单   2500   2   2  在职
ind_10  lol-19   男刀  刺客  中单  20000   2   1  在职
ind_11   lol-2   剑圣  刺客  打野  25000   6   2  在职
ind_12  lol-20  阿木木  AP  打野  13500   1   3  离职
ind_13   lol-3   寒冰  AD  射手  15000   5   2  在职
ind_14   lol-3   寒冰  AD  射手  15000   5   2  在职
ind_15   lol-4   影子  刺客  中单  30000   5   3  离职
ind_16   lol-5   蒙多  坦克  上单   8000   5   1  在职
ind_17   lol-6   小炮  AD  射手  20000   5   2  在职
ind_18   lol-7   盖伦  战士  上单  12000   5   1  在职
ind_19   lol-7   盖伦  战士  上单  12000   5   1  在职
ind_20   lol-8   蛇女  AP  中单  13000   4   3  离职
ind_21   lol-9   蛮王  战士  上单   8000   4   3  离职
"""

2>Datafram的属性

# 二、Datafram的属性
"""
shape、ndim、size
dtypes: 返回每一列的数据类型(DF的每列数据类型可以是不同的)
查看行索引、列索引和数据部分  index、columns、values
"""
print("DF1的行索引", df1.index)
print("DF1的列索引", df1.columns)
print("DF1的数据部分\n", df1.values)
print("DF1的数据部分的类型", type(df1.values))
print("DF1的数据元素类型\n", df1.dtypes)

# 针对DF的数据部分
print("DF1的shape", df1.shape)
print("DF1的ndim", df1.ndim)
print("DF1的size", df1.size)

print("DF1的类型", type(df1))

print("name列\n", df1["name"], type(df1["name"]))

"""
DF1的行索引 Index(['stu0', 'stu1', 'stu2', 'stu3'], dtype='object')
DF1的列索引 Index(['name', 'age', 'group'], dtype='object')
DF1的数据部分
 [['张三' 19 1]
 ['李四' 20 1]
 ['王五' 18 2]
 ['赵六' 19 2]]
DF1的数据部分的类型 <class 'numpy.ndarray'>
DF1的数据元素类型
 name     object
age       int64
group     int64
dtype: object
DF1的shape (4, 3)
DF1的ndim 2
DF1的size 12
DF1的类型 <class 'pandas.core.frame.DataFrame'>
name列
 stu0    张三
stu1    李四
stu2    王五
stu3    赵六
Name: name, dtype: object <class 'pandas.core.series.Series'>
"""

2、Series

1>Series的创建

import pandas as pd

# 创建Series---只有行索引和数据部分,没有列索引
s1=pd.Series(index=['stu0','stu1'],
             data=["张三","李四"])
print("s1\n",s1)
print("s1的类型\n",type(s1))
"""
s1
 stu0    张三
stu1    李四
dtype: object
s1的类型
 <class 'pandas.core.series.Series'>
"""
# DF的一列就是Series

2>Series的属性

属性同DF 的都差不多,没有列索引

3、pandas读写文件

import pandas as pd

# 读文件,read_excel可以读取后缀为xlsx、xls
# index_col 选择某一列作为行索引
# sheet_name 如果0,读第一个sheet; 1 读第二个sheet
# sheet_name 如果是None,读取所有sheet,并且组织为字典的形式
data = pd.read_excel("学生信息表.xlsx",
                     index_col=0,
                     sheet_name=None)
# print(data, type(data))
print("查看所有key", data.keys())

cls1= data["sheet1"]
print(cls1, type(cls1))


print(type(data))

print("列索引", data.columns)
print("行索引", data.index)
print("数据部分shape", data.shape)
print("数据部分\n", data.values)


# 读取 csv文件 文本文件
nba_data = pd.read_csv("data1.csv")

print("类型", type(nba_data))
print("shape信息", nba_data.shape)
print(nba_data)

# 保存到csv文件 DF名字.to_csv()
nba_data.to_csv("new_file.csv")
# 保存到excel文件 DF名字.to_excel()
nba_data.to_excel("new_file.xlsx")

猜你喜欢

转载自blog.csdn.net/weixin_45800653/article/details/121568044
今日推荐