数据分析第5天

python数据分析第5天

pandas 的应用

创建series对象

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False


%config InlineBackend.figure_format = 'svg'

# data参数表示数据,index参数表示数据的索引(标签)
# 如果没有指定index属性,默认使用整数索引(0~N-1)
ser1 = pd.Series(
    data=[320, 180, 300, 405, 120],
    index=['一季度', '二季度', '三季度', '四季度', '三季度']
)
ser1
# series对象的索引和切片
ser1[0]
ser1['一季度']

# 通过字典创建Series对象,字典的key就是Series对象的索引
ser2 = pd.Series(data={
    '一季度': 300,
    '二季度': 450,
    '三季度': 180,
    '四季度': 270,
    '三季度': 160
})
ser2
# 切片
ser2[0:2]
# 切片
ser2['一季度':'三季度']
# 花式索引
ser2[['一季度', '四季度']]
# 布尔索引
ser2[ser2 >= 200]
# 获取Series对象的值(ndarray)
ser2.values
# 获取Series对象的索引(Index对象)
ser2.index
# 有没有空值
ser2.hasnans
# 是否单调
ser2.is_monotonic
# 是否每个元素都是唯一的
ser2.is_unique

# series对象的方法
# 获取描述性统计信息
ser2.describe()
ser2.describe()['25%']
ser2.describe()['max']

ser3 = pd.Series(['apple', 'banana', 'apple', 'pitaya', 'apple', 'pitaya', 'durian'])
ser3
# 获取独一无二的元素构成数组
ser3.unique()
"""
array(['apple', 'banana', 'pitaya', 'durian'], dtype=object)
"""
# 去重
ser3.drop_duplicates()

# 不重复元素的个数
ser3.nunique()

# 判断是否重复
ser3.duplicated()

# 统计频次
ser3.value_counts()

ser4 = pd.Series(data=[10, 20, np.NaN, 30, np.NaN])
ser4

# 判断空值
ser4.isnull()

# 判断非空值
ser4.notnull()

ser4[ser4.notnull()] # 取非空值

# 删除空值
ser4.dropna()

# 填充空值
ser4.fillna(100)
#以中位数填充空值
ser4.fillna(ser4.median())
# 以前面的值填充
ser4.fillna(method='ffill')
# 以后面的值填充
ser4.fillna(method='bfill')


ser5 = pd.Series(np.arange(1, 10))
# 保留满足条件的数据,不满足的替换为指定值或置为空值
ser5.where(ser5 < 5, 99)

# 替换满足条件的值为指定值或置为空值
ser5.mask(ser5 < 5, 100)

ser7 = pd.Series(np.random.randint(30, 80, 50))

import math

# def handle_score(score):
#     return round(score ** 0.5 * 10, 1)


# temp = ser7.map(handle_score)
# 使用apply指定函数处理Series的数据
temp = ser7.apply(lambda x: math.floor(x ** 0.5 * 10))
temp

# 成绩处理后的及格人数
temp[temp >= 60].count()

# 成绩处理前的及格人数
ser7[ser7 >= 60].count()

ser8 = pd.Series(
    data=[35, 96, 12, 57, 25, 89], 
    index=['grape', 'banana', 'pitaya', 'apple', 'peach', 'orange']
)
# 根据值排序
ser8.sort_values(ascending=False)
# 根据索引排序
ser8.sort_index(inplace=True)
# 取最大的3个元素
ser8.nlargest(3)
# 取最小的2个元素
ser8.nsmallest(2)


import heapq

nums = [35, 12, 98, 57, 78, 42, 87]
# 取前三大的元素
heapq.nlargest(3, nums)
# 取前两小的元素
heapq.nsmallest(2, nums)

ser9 = pd.Series({'一季度': 400, '二季度': 520, '三季度': 180, '四季度': 380})
# 绘制柱状图
ser9.plot(figsize=(6, 3), width=0.2, kind='bar', color=['r', 'y', 'b', 'g'])
plt.grid(True, alpha=0.25, axis='y', linestyle='--')
plt.xticks(rotation=0)
plt.yticks(np.arange(0, 601, 100))
for i in range(ser9.size):
    plt.text(i, ser9[i] + 5, ser9[i], ha='center')
plt.show()

# 绘制饼图
ser9.plot(figsize=(3, 3), kind='pie', autopct='%.1f%%', 
          wedgeprops=dict(width=0.4, edgecolor='white'),
          pctdistance=0.8)
plt.ylabel('')
plt.show()

# 通过二维数组或嵌套列表创建DataFrame对象
scores = np.random.randint(60, 101, (5, 3))
courses = ['语文', '数学', '英语']
ids = [1001, 1002, 1003, 1004, 1005]
df1 = pd.DataFrame(data=scores, columns=courses, index=ids)
df1

# 通过字典创建DataFrame对象
scores = {
    '语文': [62, 72, 93, 88, 93],
    '数学': [95, 65, 86, 66, 87],
    '英语': [66, 75, 82, 69, 82],
}
ids = [1001, 1002, 1003, 1004, 1005]
df2 = pd.DataFrame(data=scores, index=ids)
df2

# 读取CSV文件创建DataFrame
df3 = pd.read_csv(
    '*.csv',
    # 用指定的列作为索引
    index_col='id',
    # 指定包围内容的字符(默认双引号)
    quotechar='|',
    # 指定读取哪些列
    usecols=['id', 'name', 'score'],
    # 指定读取的行数
    nrows=20,
    # 指定跳过的行数
    skiprows=np.arange(1, 21)
)
df3

df4 = pd.read_csv(
    '*.csv',
    # 指定文件的编码方式
    encoding='gbk'
)
df4

df5 = pd.read_csv(
    '*.tsv',
    # 指定内容分隔字符(默认逗号)
    delimiter='\t'
)
df5

# 读取Excel文件创建DataFrame
df6 = pd.read_excel(
    'data/excel/2020年销售数据.xlsx',
    header=1,
    sheet_name='Sheet3',
    usecols=['销售日期', '销售区域', '销售渠道', '品牌', '售价', '销售数量'],
    nrows=100,
    skiprows=np.arange(2, 102)
)
df6

# 连接MySQL数据库创建DataFrame
import pymysql

conn = pymysql.connect(host='127.0.0.1', port=3306, 
                       user='*', password='*', 
                       database='*', charset='utf8mb4')
conn

# 通过执行SQL语句获取数据创建DataFrame对象
df7 = pd.read_sql(
    'select dno, dname, dloc from tb_dept', 
    conn, index_col='dno'
)
df7

df8 = pd.read_sql(
    'select eno, ename, job, sal, comm, dno from tb_emp', 
    conn, index_col='eno'
)
df8

# 添加列
df8['married'] = ['未婚'] * 5 + ['已婚'] * 9
df8

# 添加行
df8.loc[9800] = ['$', '$', 12000, 800, 20, '已婚']
df8

# 删除列
df8.drop(columns=['comm', 'married'])

# 删除行
df8.drop(index=[1359, 3233, 3088])
# 重置索引
df8.reset_index(inplace=True)
df8

# 设置索引
df8.set_index('eno')

# inner join - 连接两张表
pd.merge(left=df8, right=df7, how='inner', left_on='dno', right_on='deptno')

# union - 合并两张表的数据
pd.concat((df8, df7))

# 合并文件夹有着相同数据的Excel文件
import os

filenames = os.listdir('$')
dfs = [pd.read_excel(os.path.join('$', filename), header=1) 
       for filename in filenames]
pd.concat(dfs, ignore_index=True).to_excel('汇总数据.xlsx', index=False)

# 用布尔索引筛选数据
df8[df8.sal >= 4000]


# 通过query方法筛选数据
df8.query('dno == 20 and sal >= 4000')

你可能感兴趣的:(数据分析,数据挖掘,python)