" name="sm-site-verification"/>
侧边栏壁纸
博主头像
PySuper 博主等级

千里之行,始于足下

  • 累计撰写 206 篇文章
  • 累计创建 14 个标签
  • 累计收到 2 条评论

目 录CONTENT

文章目录

Python pandas数据分析

PySuper
2020-11-25 / 0 评论 / 0 点赞 / 36 阅读 / 0 字
温馨提示:
本文最后更新于2024-05-28,若内容或图片失效,请留言反馈。 所有牛逼的人都有一段苦逼的岁月。 但是你只要像SB一样去坚持,终将牛逼!!! ✊✊✊
  • 1、使用爬虫获取到数据
  • 2、使用Pandas、Numpy进行数据分析
  • 3、matplotlib做数据可视化
  • 4、将数据展示到Web页面

一、Pandas读取excel

import pandas as pd


fileNameStr = '/home/zheng/Downloads/test.xlsx'  # 读取Ecxcel数据
xls = pd.ExcelFile(fileNameStr)
salesDf = xls.parse('Sheet1', dtype='object')

print(salesDf.head())  # 打印出前5行
print(salesDf.shape)  # 有多少行,多少列
print(salesDf.dtypes)  # 查看每列的数据类型

二、数据清洗

2.1 选择子集

subSalesDf=salesDf.loc[0:4,'购药时间':'销售数量']

2.2 列名重命名

colNameDict = {'购药时间': '销售时间'}  # 将‘购药时间’改为‘销售时间’

# inplace=False,数据框本身不会变,而会创建一个改动后新的数据框
# 默认的inplace是False,inplace=True,数据框本身会改动
salesDf.rename(columns=colNameDict, inplace=True)
print(salesDf.head())

2.3 缺失数据处理

print('删除缺失值前大小', salesDf.shape)

# 删除列(销售时间,社保卡号)中为空的行
# how='any'意为在给定的任何一列中有缺失值就删除
salesDf = salesDf.dropna(subset=['销售时间', '社保卡号'], how='any')

print('删除缺失值后大小', salesDf.shape)

2.4 数据类型转换

salesDf['销售数量'] = salesDf['销售数量'].astype('float')
salesDf['应收金额'] = salesDf['应收金额'].astype('float')
salesDf['实收金额'] = salesDf['实收金额'].astype('float')
print('转换后的数据类型:\n', salesDf.dtypes)


def splitSaletime(timeColSer):
    timeList = []
    for value in timeColSer:  # 例如2018-01-01 星期五,分割后为:2018-01-01
        dateStr = value.split(' ')[0]
        timeList.append(dateStr)

    timeSer = pd.Series(timeList)  # 将列表转行为一维数据Series类型
    return timeSer


timeSer = salesDf.loc[:, '销售时间']  # 获取“销售时间”这一列
dateSer = splitSaletime(timeSer)  # 对字符串进行分割,获取销售日期

salesDf.loc[:, '销售时间'] = dateSer  # 修改销售时间这一列的值
print(salesDf.head())

2.5 字符串转换日期

# errors='coerce': 如果原始数据不符合日期的格式,转换后的值为空值NaT
salesDf.loc[:, '销售时间'] = pd.to_datetime(
    salesDf.loc[:, '销售时间'], 
    format='%Y-%m-%d', 
    errors='coerce'
)
salesDf = salesDf.dropna(subset=['销售时间', '社保卡号'], how='any')
print(salesDf.dtypes)

2.6 数据排序

# 使用pd.sort_values方法对数据进行排序:
# by表示按那几列进行排序
# ascending=True 表示升序排列, ascending=False 表示降序排列
print('排序前的数据集', salesDf.head())

salesDf = salesDf.sort_values(by='销售时间', ascending=True)

print('排序后的数据集', salesDf.head(3))

# 重命名行号
salesDf = salesDf.reset_index(drop=True)
print(salesDf.head())

2.7 异常值处理

# 查看数据框中所有数据每列的描述统计信息
# print(salesDf.describe()) 

# 设置查询条件
querySer = salesDf.loc[:, '销售数量'] > 0

# 应用查询条件
print('删除异常值前:', salesDf.shape)
salesDf = salesDf.loc[querySer, :]
print('删除异常值后:', salesDf.shape)

三、构建模型

# 如果这两个列值同时相同,只保留1条,使用drop_duplicates将重复的数据删除
kpi1_Df = salesDf.drop_duplicates(subset=['销售时间', '社保卡号'])
totalI = kpi1_Df.shape[0]  # 总消费次数————有多少行
print('总消费次数=', totalI)

# 获取月份数
# 第1步:按销售时间升序排序
kpi1_Df = kpi1_Df.sort_values(by='销售时间', ascending=True)
kpi1_Df = kpi1_Df.reset_index(drop=True)  # 重命名行名(index)

# 第2步:获取时间范围
startTime = kpi1_Df.loc[0, '销售时间']  # 最小时间值
endTime = kpi1_Df.loc[totalI - 1, '销售时间']  # 最大时间值

# 第3步:计算月份数
daysI = (endTime - startTime).days  # 天数
monthsI = daysI // 30  # 月份数: 运算符“//”表示取整除,返回商的整数部分,例如9//2 输出结果是4
print('月份数:', monthsI)

# 用天数/30计算月份数(舍弃余数) , 最终计算月均消费次数=总消费次数 / 月份数
kpi1_I = totalI // monthsI
print('业务指标1:月均消费次数=', kpi1_I)

# 第二个指标:月均消费金额=总消费金额/月份数, 总消费金额等于实收金额取和,用sum函数很快就能得出
totalMoneyF = salesDf.loc[:, '实收金额'].sum()  # 总消费金额
monthMoneyF = totalMoneyF / monthsI  # 月均消费金额
print('业务指标2:月均消费金额=', monthMoneyF)

# 第三个指标:客单价=平均交易金额=总消费金额/总消费次数
'''
totalMoneyF:总消费金额
totalI:总消费次数
'''
pct = totalMoneyF / totalI
print('客单价:', pct)

# 第四个指标:消费趋势
# 在进行操作之前,先把数据复制到另一个数据框中,防止对之前清洗后的数据框造成影响
groupDf = salesDf
# 第1步:重命名行名(index)为销售时间所在列的值
groupDf.index = groupDf['销售时间']
# 第2步:分组
gb = groupDf.groupby(groupDf.index.month)
# 第3步:应用函数,计算每个月的消费总额
mounthDf = gb.sum()

print(mounthDf)
0
  1. 支付宝打赏

    qrcode alipay
  2. 微信打赏

    qrcode weixin

评论区