Python数据分析笔记 4

Python数据分析笔记 4

"""实现Excel的数据透视表"""
table = pd.pivot_table(df, values = ['value'], index = ['column1','column2'], columns = ['column3'], aggfunc = np.num,margins=True)
#1、df:选择待处理的DataFrame,对应Excel的框选操作,若只想筛选部分字段,则df[['column1','column2','column3','values']]
#2、value:选择我们要聚合的数值字段 ,对应Excel中的值
#3、index:选择我们的索引(行标签),对应Excel的行
#4、columns:选择我们的列字段,对应Excel的列
#5、aggfunc:选择聚合函数
#6、margins:选择是否添加行&列的小计
import numpy as np
import pandas as pd
# import pymysql
pd.set_option('display.max_rows', 9999)
pd.set_option('display.max_columns', 9999)
pd.set_option('display.float_format', lambda x: '%.3f' % x)
# - 1:各个门店在不同平台的商家实收
table = pd.pivot_table(cpc, values = ['门店实收','cpc总费用'], index = ['平台门店名称'], columns = ['平台i'], aggfunc = np.sum).fillna(0)
table
C:\Users\LENOVO\AppData\Local\Temp\ipykernel_16248\2139949438.py:2: FutureWarning: The provided callable <function sum at 0x000001BA644B93A0> is currently using DataFrameGroupBy.sum. In a future version of pandas, the provided callable will be used directly. To keep current behavior pass the string "sum" instead.
  table = pd.pivot_table(cpc, values = ['门店实收','cpc总费用'], index = ['平台门店名称'], columns = ['平台i'], aggfunc = np.sum).fillna(0)
cpc总费用门店实收
平台i美团饿了么美团饿了么
平台门店名称
利芳·一人食大盘鸡(国定路店)0.00016738.5100.00051351.750
利芳大盘鸡(国定路店)0.00011198.7100.00024088.000
拌客·干拌麻辣烫(武宁路店)0.00019624.3100.000140628.830
拌客干拌麻辣烫(武宁路店)0.000510.9000.0001597.770
拌客干拌麻辣烫(武宁路店)6939.6600.00036582.4800.000
蛙小辣·美蛙火锅杯(五角场店)0.000423.0600.0004220.500
蛙小辣·美蛙火锅杯(大宁店)0.0002085.3000.0009099.400
蛙小辣·美蛙火锅杯(宝山店)0.0009898.1200.000101526.140
蛙小辣·美蛙火锅杯(真如店)0.0006027.4600.00044432.920
蛙小辣·美蛙火锅杯(芳华路店)0.0003.6000.000152.650
蛙小辣·美蛙火锅杯(虹口足球场店)0.00013372.7000.00071286.210
蛙小辣·美蛙火锅杯(龙阳路店)0.000538.0000.0001607.480
蛙小辣·美蛙火锅杯麻辣烫(五角场店)0.000312.2100.0004866.630
蛙小辣·美蛙火锅杯麻辣烫(宝山店)0.0005786.4600.00064722.170
蛙小辣·美蛙火锅杯麻辣烫(五角场店)4.2000.000297.9000.000
蛙小辣·美蛙火锅杯(虹口足球场店)8682.9900.00043977.2500.000
蛙小辣·美蛙火锅杯(长风大悦城店)5216.9000.00033258.3300.000
蛙小辣火锅杯1567.0100.0008234.0000.000
蛙小辣火锅杯(五角场店)0.00010190.1500.00099578.180
蛙小辣火锅杯(徐汇店)0.00074.1000.000354.340
蛙小辣火锅杯(龙阳广场店)0.0001951.8300.0007486.000
蛙小辣火锅杯麻辣烫(五角场店)0.0005.8000.000263.390
蛙小辣火锅杯(五角场店)364.240649.2003108.1304642.000
蛙小辣火锅杯(合生汇店)7307.6200.00035655.8000.000
蛙小辣火锅杯(宝山店)9903.3000.00071009.6600.000
蛙小辣火锅杯(真如店)1765.970298.40016258.930939.000
蛙小辣火锅杯(金煌美食城店)683.2400.0002505.0000.000
蛙小辣美蛙火锅杯(五角场店)0.0001156.7000.0007362.000
蛙小辣美蛙火锅杯(真如店)0.000580.5000.0001468.000
蛙小辣美蛙火锅杯(亚龙美食城店)4745.2100.00017460.4400.000
蛙小辣美蛙火锅杯(大宁国际店)3909.5000.00012421.5800.000
"""”表格的合并"""
#核心思路都是采用循环,逐个拼接表格

#当想要合并不同的Excel表格(注意,要保证每个Excel表格的字段相同哦)
import numpy as np
import pandas as pd
import os

path = './test/'							#1、path:选择Excel表格所在路径
files = [i for i in os.listdir(path)]			#2、files = []:创建一个空列表,将路径中,文件or文件夹的名字装入列表
print(files)									#3、查看是否正确,如:['test1','test2']

Merge = pd.DataFrame()							#4、创建一个空的DataFrame
for i in files:									#5、for:循环遍历我们的名称列表(2),
    df = pd.read_excel(path+i)				  #6、read_excel(path+i):读取第files[i]份表格。如当i=0,files[0]='sheet1'
    Merge = pd.concat([Merge,df])				#7、concat:将df内容拼接至Merge内
Merge.to_excel(path+'excel合并.xlsx',index = None)	#8、to_excel:遍历结束后,输出我们合并后的表格

#当想要合并同一张Excel表格内的所有sheet(注意,要保证每个sheet的字段相同哦)
import numpy as np
import pandas as pd  
import os

name_list = pd.ExcelFile('./test/学习名单3.xlsx')       #1、ExcelFile:传入Excel表格
df_list = pd.DataFrame()						  #2、创建一个空DataFrame
for sheet in name_list.sheet_names:		       #3、for:循环遍历我们的名称列表(1)
    df = name_list.parse(sheet_name=sheet)    #4、name_list的属性parse:读取sheet中的内容
    df_list=pd.concat([df_list,df]) 		   #5、append:我们将读取到的sheet内容,附加到df_list中
df_list.to_excel('./test/sheet合并.xlsx',index=False)    #6、将df_list中的内容按行合并,输出


#ExcelFile():传入一个表格的路径,并赋予一个对象。
#sheet_names:他是ExcelFile()的一个方法,将Excel子工作表的名字以列表形式返回
#parse:他是ExcelFile()的一个方法
#参数sheet_name:传入子工作表的名称,可以读取里面的内容

""" 数据探索处理 """
# - 0、数据准备:导入pandas库&数据
import numpy as np
import pandas as pd
    #导入我们需要的包,并且给它起别名,方便我们调用

df = pd.read_csv('./cpc.csv',encoding='gbk') 
    #df--给我们导入的数据命名为df
    #pd--调用pandas
    #read_csv()--pandas常用的读取数据函数
    #('文件名')--需要导入的数据文件名
# - 1、了解数据
df.info() #了解数据框架--我们数据的行列、字段的类别等概况
    #rangeIndex--数据总体的行数
    #data columns--数据总体的字段
    #int64/object/float64...--字段数据类型,object可理解为字符串
    #xxx non-null--非空的记录数
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1177 entries, 0 to 1176
Data columns (total 24 columns):
 #   Column      Non-Null Count  Dtype  
---  ------      --------------  -----  
 0   updateTime  1177 non-null   object 
 1   平台i         1177 non-null   object 
 2   门店ID        1177 non-null   int64  
 3   平台门店名称      1177 non-null   object 
 4   日期          1177 non-null   object 
 5   cpc单次点击费用   1165 non-null   float64
 6   cpc总费用      1177 non-null   float64
 7   cpc曝光量      1177 non-null   int64  
 8   cpc访问量      1177 non-null   int64  
 9   gmvroi      1177 non-null   float64
 10  下单转换率       1177 non-null   float64
 11  单均gmv       1177 non-null   float64
 12  单均实收        1177 non-null   float64
 13  实收roi       1177 non-null   float64
 14  无效订单        1168 non-null   float64
 15  有效订单        1168 non-null   float64
 16  自增主键        1177 non-null   int64  
 17  自然曝光量       1165 non-null   float64
 18  自然访问量       1165 non-null   float64
 19  门店下单量       1165 non-null   float64
 20  门店实收        1168 non-null   float64
 21  门店曝光量       1165 non-null   float64
 22  门店营业额       1168 non-null   float64
 23  门店访问量       1165 non-null   float64
dtypes: float64(16), int64(4), object(4)
memory usage: 220.8+ KB
df.head(10) #了解详细数据
    #可以看到我们表格内具体的数据内容
    #head()--括号内不加参数,默认为5,即显示5行
updateTime平台i门店ID平台门店名称日期cpc单次点击费用cpc总费用cpc曝光量cpc访问量gmvroi下单转换率单均gmv单均实收实收roi无效订单有效订单自增主键自然曝光量自然访问量门店下单量门店实收门店曝光量门店营业额门店访问量
02019/12/12 11:54美团8184590蛙小辣火锅杯(合生汇店)2019-12-101.300225.65027111737.4300.17057.48019.8002.5600.00059.00015016031427.000159.00056.0001167.9704138.0003391.380332.000
12019/12/12 11:54美团8223184蛙小辣美蛙火锅杯(大宁国际店)2019-12-101.540261.10036651694.3000.13052.99018.8801.5300.00035.000150160511.00086.00032.000660.7303676.0001854.760255.000
22019/12/12 11:54美团8106681蛙小辣·美蛙火锅杯(长风大悦城店)2019-12-101.380177.50021151296.7500.18051.49020.3802.6701.00053.0001502265874.000165.00053.0001080.3102989.0002728.720294.000
32019/12/12 11:54美团8165842蛙小辣·美蛙火锅杯(虹口足球场店)2019-12-101.470240.30029371647.4300.19056.35019.2502.5402.00064.0001502274614.000162.00063.0001231.8603551.0003606.100326.000
42019/12/12 11:54饿了么2001220953利芳·一人食大盘鸡(国定路店)2019-12-101.550623.50041904015.3500.17049.69012.7101.3700.000132.00015025231872.000387.000132.0001677.9606062.0006558.490788.000
52019/12/12 11:54饿了么2000555792蛙小辣·美蛙火锅杯(虹口足球场店)2019-12-101.610207.80016281293.1700.09056.10018.2001.0300.00032.0001502706802.000223.00032.000582.4402430.0001795.340352.000
62019/12/12 11:54饿了么2001104355蛙小辣·美蛙火锅杯(宝山店)2019-12-101.250198.50020431596.5200.13064.65025.6202.5800.00054.00015027361108.000254.00052.0001383.3103151.0003491.020413.000
72019/12/12 11:54饿了么2000507076蛙小辣火锅杯(五角场店)2019-12-101.350166.40017051236.4000.15057.81021.2802.3601.00063.00015029671470.000284.00061.0001340.4703175.0003642.100407.000
82019/12/12 11:54饿了么2001020019蛙小辣·美蛙火锅杯(真如店)2019-12-101.510140.3001376934.8200.14053.45014.6601.3200.00046.00015029871394.000245.00046.000674.1602770.0002458.600338.000
92019/12/12 12:49美团8106681蛙小辣·美蛙火锅杯(长风大悦城店)2019-12-091.400195.35023291406.8700.20047.13017.2002.5103.00063.0001503654839.000160.00061.0001083.5903168.0002969.080300.000
df.drop(columns='updateTime',inplace = True)#当我们通过上一步:df.head()查看数据内容后,可以删除我们认为不需要的字段
    #inplace--我们直接替换原有的数据
#- 3、数值探索

df.describe()#我们对表格内的数值型字段进行描述性统计
    #count--计数
    #mean--平均值
    #std--标准差
    #min--最小值
    #25%/50%/75%--分位值
    #max--最大值
门店IDcpc单次点击费用cpc总费用cpc曝光量cpc访问量gmvroi下单转换率单均gmv单均实收实收roi无效订单有效订单自增主键自然曝光量自然访问量门店下单量门店实收门店曝光量门店营业额门店访问量
count1177.0001165.0001177.0001177.0001177.0001177.0001177.0001177.0001177.0001177.0001168.0001168.0001177.0001165.0001165.0001165.0001168.0001165.0001168.0001165.000
mean1102707722.1041.390129.5801350.98691.3118.5500.18957.69420.6993.0530.60141.9883023888.6081245.313124.75040.894789.7632604.0822298.817216.701
std968178797.9020.304134.5391256.42387.90815.7240.0639.2285.2445.6021.18835.5791433359.6341206.364101.60834.501566.8411813.4941728.387161.656
min8052557.0000.0200.0000.0000.0000.0000.0000.0000.0000.0000.0004.0001501603.000-5534.000-427.0000.00030.0000.000164.0000.000
25%8491999.0001.24039.910466.00029.0006.0400.15052.99017.8202.0200.00017.0001872058.000492.00050.00017.000375.5951123.0001040.51786.000
50%2000507076.0001.38076.200863.00057.0007.5900.19057.81020.5302.6600.00026.0002538079.000812.00092.00026.000587.6452016.0001609.425157.000
75%2001104355.0001.540190.0001950.000133.0009.8500.23062.74023.5303.6001.00061.2503775030.0001599.000169.00060.0001100.1523605.0003296.950314.000
max2001572992.0002.980846.4007812.000502.000534.6600.42090.76047.320189.32012.000232.0007684897.0007153.000745.000224.0003780.11011066.00011012.760985.000
"""

小练习
我们已经拥有了本地数据cpc,现在,我们需要使用sql获取云端数据shop,与本地数据进行连接,并完成以下操作

1、查看各平台在6、7月的GMV占比
2、查看6、7月各周的总GMV情况
3、查看6、7月各周的转化率情况
4、查看6、7月每天各个门店的GMV,门店实收,并按照门店实收进行排名。(输出字段:日期-门店名称-GMV-门店实收-排名)
答案可参考Practise.ipynb

"""
"""matplotlib"""
# DataFrame与Seires可以直接调用matplotlib的plot方法
# 想了解更多细节的家人们可以跳转至官网查看
# https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.plot.html?highlight=plot#pandas.DataFrame.plot
%matplotlib notebook
%matplotlib inline
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']#设置可以显示中文
plt.rcParams['axes.unicode_minus'] = False #正常显示负号
import pandas as pd
olpc = pd.read_csv('Tokyo 2021 dataset.csv') #读取文件中东京奥运会的CSV表格
olpc.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 93 entries, 0 to 92
Data columns (total 8 columns):
 #   Column         Non-Null Count  Dtype 
---  ------         --------------  ----- 
 0   Rank           93 non-null     int64 
 1   Team/NOC       93 non-null     object
 2   Gold Medal     93 non-null     int64 
 3   Silver Medal   93 non-null     int64 
 4   Bronze Medal   93 non-null     int64 
 5   Total          93 non-null     int64 
 6   Rank by Total  93 non-null     int64 
 7   NOCCode        93 non-null     object
dtypes: int64(6), object(2)
memory usage: 5.9+ KB
top5 = olpc[olpc.Rank<=5] #将排名>5的数据命名为top5
top5.rename(columns={'Team/NOC':'Team'},inplace=True) #给字段Team/NOC 改名为 Team
top5
C:\Users\LENOVO\AppData\Local\Temp\ipykernel_16248\4082916704.py:2: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  top5.rename(columns={'Team/NOC':'Team'},inplace=True) #给字段Team/NOC 改名为 Team
RankTeamGold MedalSilver MedalBronze MedalTotalRank by TotalNOCCode
01United States of America3941331131USA
12People's Republic of China383218882CHN
23Japan271417585JPN
34Great Britain222122654GBR
45ROC202823713ROC
# 基础图表
# 每一个单元格都有自己的figure(),不然图表会被后面的代码篡改哦
plt.figure()
plt.plot(top5['NOCCode'],top5['Gold Medal'])#plot为折线图,分别传入参数x,y对应横纵坐标
[<matplotlib.lines.Line2D at 0x1ba68ed7e10>]

在这里插入图片描述

plt.figure()
plt.bar(top5['NOCCode'],top5['Gold Medal'])#bar为柱状图,分别传入参数x,y对应横纵坐标
<BarContainer object of 5 artists>

在这里插入图片描述

plt.figure()
plt.barh(top5['NOCCode'],top5['Gold Medal']) #barh为水平柱状图,分别传入参数x,y对应横纵坐标
<BarContainer object of 5 artists>

在这里插入图片描述

plt.figure()
plt.pie(top5['Gold Medal']) #pie为饼图,需要传入的是一个 Seires
([<matplotlib.patches.Wedge at 0x1ba68c4ab90>,
  <matplotlib.patches.Wedge at 0x1ba69704a90>,
  <matplotlib.patches.Wedge at 0x1ba69705410>,
  <matplotlib.patches.Wedge at 0x1ba69706890>,
  <matplotlib.patches.Wedge at 0x1ba69707d10>],
 [Text(0.7348702653319799, 0.8185143206633013, ''),
  Text(-0.8786572668872328, 0.6617865270208049, ''),
  Text(-0.8025133929575279, -0.7523112747552017, ''),
  Text(0.2579404140090271, -1.0693300439157463, ''),
  Text(0.9996993595783734, -0.45891305326672754, '')])

在这里插入图片描述

plt.figure()
plt.scatter(top5['NOCCode'],top5['Gold Medal']) #scatter是散点图,传入两个 数值型的字段
<matplotlib.collections.PathCollection at 0x1ba68dfcb10>

在这里插入图片描述

plt.figure()
plt.hist(top5['Gold Medal'],bins=5) #hist为直方图,传入一个Serires,bins可以设置你的桶大小
(array([2., 1., 0., 0., 2.]),
 array([20. , 23.8, 27.6, 31.4, 35.2, 39. ]),
 <BarContainer object of 5 artists>)

在这里插入图片描述

plt.figure()
plt.plot(top5['NOCCode'],top5['Gold Medal'])
plt.ylim(20,40) #设置你的y轴范围
#若想设置x轴,则输入 plt.xlim()
(20.0, 40.0)

在这里插入图片描述

plt.figure()
plt.plot(top5['NOCCode'],top5['Gold Medal'])
plt.xlabel('国家简称')
plt.ylabel('金牌数目')
#给坐标命名
Text(0, 0.5, '金牌数目')

在这里插入图片描述

plt.figure()
plt.plot(top5['NOCCode'],top5['Gold Medal'],label = '金牌数目') #添加一个参数 label,然后输入你的标签
plt.legend() #要码出这行代码,标签才会显示哦
#增加图例
<matplotlib.legend.Legend at 0x1ba68e386d0>

在这里插入图片描述

plt.figure()
plt.plot(top5['NOCCode'],top5['Gold Medal'])
for x,y in zip(top5['NOCCode'],top5['Gold Medal']):
    plt.text(x,y+0.1,'%d' % y,ha = 'center',va = 'bottom')
#增加标注

在这里插入图片描述

  • 13
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值