数据分析_表和表的运用

kobe_df = pd.read_csv('data/Kobe_data.csv', index_col='shot_id')

ser = kobe_df.action_type + '-' + kobe_df.combined_shot_type
ser.value_counts().index[0]


kobe_df.drop_duplicates('game_id').opponent.value_counts().index[0]


kobe_df['shot_made_flag'] = kobe_df.shot_made_flag.fillna(0).map(int)
temp = kobe_df[kobe_df.shot_made_flag == 1].shot_type

temp.str.extract(r'(\d+)')[0].map(int).sum()
import pymysql

conn = pymysql.connect(host='47.104.31.138', port=3306,
                       user='guest', password='Guest.618',
                       database='hrs', charset='utf8mb4')
dept_df = pd.read_sql('select dno, dname, dloc from tb_dept', conn)
dept_df
emp_df = pd.read_sql(
    sql='select eno, ename, job, mgr, sal, comm, dno from tb_emp',
    con=conn,

)

pd.merge(emp_df, dept_df, how='inner', on='dno').set_index('eno')

emp_df[(emp_df.dno == 20) & (emp_df.sal >= 5000)]

emp_df.query('dno == 20 and sal >= 5000')

emp_df.drop(index=emp_df[emp_df.dno != 20].index, inplace=True)

emp_df.drop(columns=['mgr', 'dno'], inplace=True)


emp_df.rename(columns={'sal': 'salary', 'comm': 'allowance'}, inplace=True)


emp_df.reset_index(inplace=True)

emp_df.set_index('ename', inplace=True)
emp_df

emp_df.reindex(columns=['salary', 'job'])

emp_df.reindex(index=['李莫愁', '张三丰', '乔峰'])

import itertools

names = ['高新', '犀浦', '新津']
years = ['2018', '2019']
groups = ['A', 'B']

for name, year, group in itertools.product(names, years, groups):
    print(name, year, group)

import itertools

names = ['高新', '犀浦', '新津']
years = ['2018', '2019']
dfs = [pd.read_excel(f'data/小宝剑大药房({name}店){year}年销售数据.xlsx', header=1)
       for name, year in itertools.product(names, years)]

pd.concat(dfs, ignore_index=True).to_excel('小宝剑大药房2018-2019年汇总数据.xlsx')
emp_df.isnull()

youtube_df.tail(10)
youtube_df.head(10)
youtube_df.duplicated('video_id')


youtube_df = youtube_df.drop_duplicates('video_id', keep='first')
youtube_df
emp_df.replace('程序员', '程序猿', inplace=True)
Get value at specified row/column pair
>>> df.at[4, 'B']
2
Set value at specified row/column pair

>>> df.at[4, 'B'] = 10
>>> df.at[4, 'B']
10
emp_df.at[2, 'job'] = '程序媛'


emp_df.replace(regex='程序[猿媛]', value='程序员')

emp_df['job'] = emp_df.job.str.replace('程序[猿媛]', '程序员', regex=True)
temp = pd.DataFrame({'A': range(3), 'B': range(1, 4)})

temp.apply(np.sqrt)

temp.apply(np.sum)

temp.apply(np.sum, axis=1)

temp.transform(np.sqrt)

temp.transform([np.exp, np.sqrt])


student_df['stu_sex'] = student_df.stu_sex.transform(lambda x: '男' if x == 1 else '女')
student_df

temp = youtube_df.sort_values(by=['likes', 'views'], ascending=[False, True])

youtube_df.drop_duplicates('video_id', keep='last').nlargest(10, 'likes')
youtube_df['hot_value'] = youtube_df.views + youtube_df.likes + youtube_df.dislikes + youtube_df.comment_count

youtube_df.groupby(by='channel_title').hot_value.sum()

def ptp(g):
    return g.max() - g.min()

temp = youtube_df.groupby(by='channel_title')
temp[['hot_value', 'likes']].agg(['sum', 'max', 'min', ptp])
student_df.stu_sex.value_counts()

student_df.groupby('stu_sex').count()

temp = student_df.groupby(by=['collid', 'stusex']).count()

按多个分类

temp.loc[(1, '男')]


student_df.pivot_table(index='stu_sex', values='stu_id', aggfunc='count')


student_df.pivot_table(index=['col_id', 'stu_sex'], values='stuid', aggfunc='count')

temp = student_df.pivot_table(
    index='col_id',
    columns='stu_sex',
    values='stu_id',
    aggfunc='count',
    fill_value=0
)

df1 = pd.DataFrame({
    "类别": ["手机", "手机", "手机", "手机", "手机", "电脑", "电脑", "电脑", "电脑"],
    "品牌": ["华为", "华为", "华为", "小米", "小米", "华为", "华为", "小米", "小米"],
    "等级": ["A类", "B类", "A类", "B类", "C类", "A类", "B类", "C类", "A类"],
    "A组": [1, 2, 2, 3, 3, 4, 5, 6, 7],
    "B组": [2, 4, 5, 5, 6, 6, 8, 9, 9]
})


df1.pivot_table(index='类别', values='A组', aggfunc=np.sum)


df1.pivot_table(index='类别', columns='品牌', values='A组', aggfunc=np.sum)

df2 = pd.DataFrame({
    '类别': ['水果', '水果', '水果', '蔬菜', '蔬菜', '肉类', '肉类'],
    '产地': ['美国', '中国', '中国', '中国', '新西兰', '新西兰', '美国'],
    '名称': ['苹果', '梨', '草莓', '番茄', '黄瓜', '羊肉', '牛肉'],
    '数量': [5, 5, 9, 3, 2, 10, 8],
    '价格': [5.8, 5.2, 10.8, 3.5, 3.0, 13.1, 20.5]
})


pd.crosstab(
    index=df2['类别'],
    columns=df2['产地'],
    values=df2['数量'],
    aggfunc=np.sum,
    margins=True,
    margins_name='总计'
).fillna(0).applymap(int)

形成一个元素来自均值是μ,方差为σ正态分布,n行m列的数组

heights = np.round(np.random.normal(172, 8, 500), 1)
temp_df = pd.DataFrame(data=heights, index=np.arange(1001, 1501), columns=['身高'])

bins = [0, 150, 160, 170, 180, 190, 200, np.inf]

cate = pd.cut(temp_df['身高'], bins, right=False)
result = temp_df.groupby(cate).count()
luohu_df = pd.read_csv('data/2018年北京积分落户数据.csv', index_col='id')
pd.to_datetime(luohu_df.birthday)


from datetime import datetime

ref_date = datetime(2018, 7, 1)
ser = ref_date - pd.to_datetime(luohu_df.birthday)
luohu_df['age'] = ser.dt.days // 365
luohu_df


temp = luohu_df.company.value_counts()
temp[temp > 20]


bins = np.arange(30, 61, 5)
cate = pd.cut(luohu_df.age, bins)
temp = luohu_df.groupby(cate).name.count()
temp.plot(kind='bar')
for i in range(temp.size):
    plt.text(i, temp[i], temp[i], ha='center')
plt.xticks(
    np.arange(temp.size),
    labels=[f'{index.left}~{index.right}岁' for index in temp.index],
    rotation=30
)
plt.show()

bins = np.arange(90, 126, 5)
cate = pd.cut(luohu_df.score, bins, right=False)
luohu_df.groupby(cate).name.count()

lagou_df = pd.read_csv(
    'data/lagou.csv',
    index_col='no',
    usecols=['no', 'city', 'companyFullName', 'positionName', 'industryField', 'salary']
)
lagou_df.shape


lagou_df = lagou_df[lagou_df.positionName.str.contains('数据分析')]
lagou_df.tail()

temp = lagou_df.salary.str.extract('(\d+)[kK]?-(\d+)[kK]?').applymap(int)
temp

lagou_df.loc[:, 'salary'] = temp.mean(axis=1)

lagou_df.city.value_counts()

ser = lagou_df.groupby('city').companyFullName.count()
ser.plot(figsize=(10, 4), kind='bar', color=['r', 'g', 'b', 'y'], width=0.8)

plt.grid(True, alpha=0.25, linestyle=':', axis='y')

plt.xticks(rotation=0)

plt.yticks(np.arange(0, 501, 50))

plt.xlabel('')

plt.title('各大城市岗位数量')
for i in range(ser.size):

    plt.text(i, ser[i], ser[i], ha='center')
plt.show()

temp = lagou_df.industryField.str.split(pat='[丨,]', expand=True)
lagou_df['modifiedIndustryField'] = temp[0]
ser = lagou_df.groupby('modifiedIndustryField').companyFullName.count()
explodes = [0, 0.15, 0, 0, 0.05, 0, 0, 0, 0, 0]
ser.nlargest(10).plot(
    figsize=(6, 6),
    kind='pie',
    autopct='%.2f%%',
    pctdistance=0.75,
    shadow=True,
    explode=explodes,
    wedgeprops={
        'edgecolor': 'white',
        'width': 0.5
    }
)
plt.ylabel('')
plt.show()


ser = np.round(lagou_df.groupby('city').salary.mean(), 2)
ser.plot(figsize=(8, 4), kind='bar')
ser.plot(kind='line', color='red', marker='o', linestyle='--')
plt.show()

提取2019年的订单数据


from datetime import datetime

start = datetime(2019, 1, 1)
end = datetime(2019, 12, 31, 23, 59, 59)
order_df.drop(index=order_df[order_df.orderTime < start].index, inplace=True)
order_df.drop(index=order_df[order_df.orderTime > end].index, inplace=True)
order_df.shape

处理支付时间早于下单时间的数据


order_df.drop(order_df[order_df.payTime < order_df.orderTime].index, inplace=True)
order_df.shape

折扣字段的处理


order_df['discount'] = np.round(order_df.payment / order_df.orderAmount, 4)
mean_discount = np.mean(order_df[order_df.discount  1].discount)
order_df['discount'] = order_df.discount.apply(lambda x: x if x  1 else mean_discount)
order_df['payment'] = order_df.orderAmount * order_df.discount

显示整体分析

print(f'GMV: {order_df.orderAmount.sum() / 10000:.4f}万元')
print(f'总销售额: {order_df.payment.sum() / 10000:.4f}万元')
real_total = order_df[order_df.chargeback == "否"].payment.sum()
print(f'实际销售额: {real_total / 10000:.4f}万元')
back_rate = order_df[order_df.chargeback == '是'].orderID.size / order_df.orderID.size
print(f'退货率: {back_rate * 100:.2f}%')
print(f'客单价:{real_total / order_df.userID.nunique():.2f}元')
print(order_df[order_df.chargeback == '是'].orderID.size)

np.mean(order_df[order_df.discount


&#x663E;&#x793A;&#x6574;&#x4F53;&#x5206;&#x6790;

`python
print(f'GMV: {order_df.orderAmount.sum() / 10000:.4f}&#x4E07;&#x5143;')
print(f'&#x603B;&#x9500;&#x552E;&#x989D;: {order_df.payment.sum() / 10000:.4f}&#x4E07;&#x5143;')
real_total = order_df[order_df.chargeback == "&#x5426;"].payment.sum()
print(f'&#x5B9E;&#x9645;&#x9500;&#x552E;&#x989D;: {real_total / 10000:.4f}&#x4E07;&#x5143;')
back_rate = order_df[order_df.chargeback == '&#x662F;'].orderID.size / order_df.orderID.size
print(f'&#x9000;&#x8D27;&#x7387;: {back_rate * 100:.2f}%')
print(f'&#x5BA2;&#x5355;&#x4EF7;&#xFF1A;{real_total / order_df.userID.nunique():.2f}&#x5143;')
print(order_df[order_df.chargeback == '&#x662F;'].orderID.size)

Original: https://blog.csdn.net/niki__/article/details/121624646
Author: niki__
Title: 数据分析_表和表的运用

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/743852/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • Django2登入demo说明rest_framework基本使用

    1.rest_framework配置 1.安装: pip install djangorestframework 2.setting配置 增加: ‘rest_framework’,…

    Python 2023年8月5日
    055
  • yolov5目标框预测

    yolov5目标检测模型中,对模型结构的描述较多,也容易理解。但对如何获得目标预测方面描述较少,或总感觉云山雾罩搞不清楚。最近查阅一些资料,并加上运行yolov5程序的感受,总结一…

    Python 2023年9月30日
    043
  • Spring AOP统一功能处理(切面、切点、连接点、通知)

    目录 一、 AOP的一些前置知识 1.1什么是Aop 1.2 AOP的作用 1.3AOP基础组成 二、SpringAOP的实现 2.1添加SpringAOP框架支持 2.2定义切面…

    Python 2023年11月6日
    038
  • python pandas数据处理和基本操作

    本文介绍的方法均为我在做作业是常用的方法,要是有不对的地方还请大神指正 本文示例文件 &#x6392;&#x540D;,&#x59D3;&#x540…

    Python 2023年8月7日
    066
  • 小白入门——Python标准库和第三方库简介

    首先简要介绍如何查看python库安装位置,常见Python标准库和常见Python第三方库简介。 查看python库安装位置 1、使用pip list查看 在cmd中输入pyth…

    Python 2023年9月3日
    055
  • 元组(tuple)

    4.5 元组(tuple) 元组这种数据类型和列表非常相似,也是一种序列。和列表的不同之处在于存放到元组内的数据不能直接修改。元组是一种可迭代对象。使用元组可以使程序运行性能提升,…

    Python 2023年11月1日
    040
  • 手部21个关键点检测+手势识别-[MediaPipe]

    MediaPipe 是一款由 Google Research 开发并开源的多媒体机器学习模型应用框架,可以直接调用其API完成目标检测、人脸检测以及关键点检测等。本篇文章介绍其手部…

    Python 2023年8月2日
    099
  • Django设置SECRET_KEY

    在我们做完django项目后,向生产环境部署时,为了避免一些敏感信息被有心人利用,我们应该将其保护起来,比如说在settings配置中的一些密码等内容存在操作系统内,通过调用来使用…

    Python 2023年8月4日
    044
  • pandas csv转json_十分钟学习pandas! pandas常用操作总结!

    学习Python, 当然少不了pandas,pandas是python数据科学中的必备工具,熟练使用pandas是从sql boy/girl 跨越到一名优秀的数据分析师傅的必备技能…

    Python 2023年8月8日
    034
  • Spring Boot 中使用 Swagger

    Spring Boot 使用 Swagger 自动生成接口文档 前后端分离开发,后端需要编写接⼝说明⽂档,会耗费⽐较多的时间。swagger 是⼀个⽤于⽣成服务器接⼝的规范性⽂档,…

    Python 2023年10月16日
    032
  • gif动态图片生成器,多张图片组合后生成动图…

    这个小工具制作的目的是为了将多张图片组合后生成一张动态的GIF图片。设置界面化的操作,只需要将选中的图片导入最后直接生成动态图片。 完整的源代码需要到正文的末尾,完整的源代码获取方…

    Python 2023年5月24日
    073
  • MacOS系统下matplotlib中SimHei中文字体缺失报错的解决办法

    文章目录 * – 问题描述 – 解决方法: – + Step 1. 在终端进入python3环境,查看matplotlib字体路径: + Ste…

    Python 2023年9月2日
    088
  • Python基础知识_列表(List)

    列表是一个有序且可更改的集合。列表允许重复的成员。在 Python 中,列表用方括号编写。示例: list = ["apple", "banana&q…

    Python 2023年8月25日
    035
  • 彻底掌握Makefile(三)

    彻底掌握Makefile(三) 前言 在前面的文章彻底掌握Makefile(一)和彻底掌握Makefile(二)当中,我们简要的介绍了一些常见的makefile使用方法,在本篇文章…

    Python 2023年10月21日
    045
  • 关于在django框架中在admin页面下添加自定义按钮并实现功能

    关于如何在django中admin页面下添加自定义按钮并实现功能 最近使用Django的admin页面开发了一个产品信息管理系统,由于需求的不断增加,需要在admin页面自定义一些…

    Python 2023年8月5日
    098
  • 粒子群优化算法及其应用

    产生背景 粒子群优化(Particle Swarm Optimization, PSO)算法是由美国普渡大学的Kennedy和Eberhart于1995年提出,它的基本概念源于对鸟…

    Python 2023年9月16日
    038
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球