溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

pandas數(shù)據(jù)處理進階

發(fā)布時間:2020-06-22 18:19:23 來源:網(wǎng)絡(luò) 閱讀:474 作者:ckllf 欄目:編程語言

  一、pandas的統(tǒng)計分析

  1、關(guān)于pandas 的數(shù)值統(tǒng)計(統(tǒng)計detail 中的 單價的相關(guān)指標)

  import pandas as pd

  # 加載數(shù)據(jù)

  detail = pd.read_excel("./meal_order_detail.xlsx")

  print("detail :\n", detail)

  print("detail 的列索引名稱:\n", detail.columns)

  print("detail 的形狀:\n", detail.shape)

  print("detail 數(shù)據(jù)類型:\n", detail.dtypes)

  print("amounts 的最大值:\n",detail.loc[:,'amounts'].max())

  print("amounts 的最小值:\n",detail.loc[:,'amounts'].min())

  print("amounts 的均值:\n",detail.loc[:,'amounts'].mean())

  print("amounts 的中位數(shù):\n",detail.loc[:,'amounts'].median())

  print("amounts 的方差:\n",detail.loc[:,'amounts'].var())

  print("amounts 的describe:\n",detail.loc[:,'amounts'].describe())

  # 對于兩列的統(tǒng)計結(jié)果

  print("amounts 的describe:\n",detail.loc[:,['counts','amounts']].describe())

  print("amounts 的describe:\n",detail.loc[:,['counts','amounts']].describe())

  print("amounts 的describe:\n",detail.loc[:,'amounts'].describe())

  print("amounts 的describe:\n",detail.loc[:,'counts'].describe())

  print("amounts 的極差:\n",detail.loc[:,'amounts'].ptp())

  print("amounts 的標準差:\n",detail.loc[:,'amounts'].std())

  print("amounts 的眾數(shù):\n",detail.loc[:,'amounts'].mode()) # 返回眾數(shù)的數(shù)組

  print("amounts 的眾數(shù):\n",detail.loc[:,'counts'].mode()) # 返回眾數(shù)的數(shù)組

  print("amounts 的非空值的數(shù)目:\n",detail.loc[:,'amounts'].count())

  print("amounts 的最大值的位置:\n",detail.loc[:,'amounts'].idxmax()) # np.argmax()

  print("amounts 的最小值的位置:\n",detail.loc[:,'amounts'].idxmin()) # np.argmin()

  2、pandas對于非數(shù)值型數(shù)據(jù)的統(tǒng)計分析

  (1)對于dataframe轉(zhuǎn)化數(shù)據(jù)類型,其他類型 轉(zhuǎn)化為object類型

  detail.loc[:,'amounts'] = detail.loc[:,'amounts'].astype('object')

  (2)類別型數(shù)據(jù)

  detail.loc[:,'amounts'] = detail.loc[:,'amounts'].astype('category')

  print("統(tǒng)計類別型數(shù)據(jù)的describe指標:\n",detail.loc[:, 'amounts'].describe())

  (3)統(tǒng)計實例

  #### 統(tǒng)計在detail中 最火的菜品以及賣出的份數(shù)

  ## 若白飯算菜

  detail.loc[:, 'dishes_name'] = detail.loc[:, 'dishes_name'].astype('category')

  print("按照dishes_name統(tǒng)計描述信息:\n", detail.loc[:, 'dishes_name'].describe())

  ## 若白飯不算菜 ,把白飯刪除,再統(tǒng)計

  # drop labels,行的名稱, axis =0,inplace = True

  # 定位到白飯的行

  bool_id = detail.loc[:, 'dishes_name'] == '白飯/大碗'

  # 進行 獲取行名稱

  index = detail.loc[bool_id, :].index

  # 進行刪除

  detail.drop(labels=index, axis=0, inplace=True)

  # 在進行轉(zhuǎn)化類型

  detail.loc[:, 'dishes_name'] = detail.loc[:, 'dishes_name'].astype('category')

  # 在進行統(tǒng)計描述信息

  print("按照dishes_name統(tǒng)計描述信息:\n", detail.loc[:, 'dishes_name'].describe())

  ## 統(tǒng)計在detail 中訂單中菜品最多的

  # 將 order_id 轉(zhuǎn)化為類別型數(shù)據(jù) ,再 進行describe

  detail.loc[:, 'order_id'] = detail.loc[:, 'order_id'].astype("category")

  # 統(tǒng)計描述

  print("按照order_id統(tǒng)計描述信息為:\n", detail.loc[:, 'order_id'].describe())

  二、pandas時間數(shù)據(jù)

  datetime64[ns] ---numpy 里面的時間點類

  Timestamp ---pandas 默認的時間點類型----封裝了datetime64[ns]

  DatetimeIndex ---pandas 默認支持的時間序列結(jié)構(gòu)

  1、可以通過 pd.to_datetime 將時間點數(shù)據(jù)轉(zhuǎn)化為pandas默認支持的時間點數(shù)據(jù)

  res = pd.to_datetime("2016/01/01")

  print("res:\n",res)

  print("res 的類型:\n",type(res))

  2、時間序列轉(zhuǎn)化 --可以通過pd.to_datetime 或者pd.DatetimeIndex將時間序列轉(zhuǎn)化為pandas默認支持的時間序列結(jié)構(gòu)

  res = pd.to_datetime(['2016-01-01', '2016-01-01', '2016-01-01', '2011-01-01'])

  res1 = pd.DatetimeIndex(['2016-01-01', '2016-01-02', '2016-02-05', '2011-09-01'])

  print("res:\n", res)

  print("res 的類型:\n", type(res))

  print("res1:\n", res1)

  print("res1 的類型:\n", type(res1))

  3、

  import pandas as pd

  # #加載數(shù)據(jù)

  detail = pd.read_excel("./meal_order_detail.xlsx")

  # print("detail :\n",detail)

  print("detail 的列索引名稱:\n", detail.columns)

  print("detail 的形狀:\n", detail.shape)

  # print("detail 數(shù)據(jù)類型:\n",detail.dtypes)

  print("*" * 80)

  # 獲取place_order_time列

  print(detail.loc[:, 'place_order_time'])

  # 轉(zhuǎn)化為pandas默認支持的時間序列結(jié)構(gòu)

  detail.loc[:, 'place_order_time'] = pd.to_datetime(detail.loc[:, 'place_order_time'])

  # print(detail.dtypes)

  print("*" * 80)

  # 獲取該時間序列的屬性---可以通過列表推導(dǎo)式來獲取時間點的屬性

  year = [i.year for i in detail.loc[:, 'place_order_time']]

  print("年:\n", year)

  month = [i.month for i in detail.loc[:, 'place_order_time']]

  print("月:\n", month)

  day = [i.day for i in detail.loc[:, 'place_order_time']]

  print("日:\n", day)

  quarter = [i.quarter for i in detail.loc[:, 'place_order_time']]

  print("季度:\n", quarter)

  # 返回對象

  weekday = [i.weekday for i in detail.loc[:, 'place_order_time']]

  print("周幾:\n", weekday)

  weekday_name = [i.weekday_name for i in detail.loc[:, 'place_order_time']]

  print("周幾:\n", weekday_name)

  is_leap_year = [i.is_leap_year for i in detail.loc[:, 'place_order_time']]

  print("是否閏年:\n", is_leap_year)

  4、時間加減

  import pandas as pd

  res = pd.to_datetime("2016-01-01")

  print("res:\n", res)

  print("res 的類型:\n", type(res))

  print("時間推后一天:\n", res + pd.Timedelta(days=1))

  print("時間推后一小時:\n", res + pd.Timedelta(hours=1))

  detail.loc[:, 'place_over_time'] = detail.loc[:, 'place_order_time'] + pd.Timedelta(days=1)

  print(detail)

  ## 時間差距計算

  res = pd.to_datetime('2019-10-9') - pd.to_datetime('1996-11-07')

  print(res)

  5、獲取本機可以使用的最初時間 和最后使用的時間節(jié)點

  print(pd.Timestamp.min)

  print(pd.Timestamp.max)

  三、分組聚合

  import pandas as pd

  import numpy as np

  # 加載數(shù)據(jù)

  users = pd.read_excel("./users.xlsx")

  print("users:\n", users)

  print("users 的列索引:\n", users.columns)

  print("users 的數(shù)據(jù)類型:\n", users.dtypes)

  # 根據(jù)班級分組、統(tǒng)計學(xué)員的班級的平均年齡

  # groupby 分組

  # by ---指定分組的列,可以是單列 也可以是多列

  # res = users.groupby(by='ORGANIZE_NAME')['age'].mean()

  # 按照單列進行分組,統(tǒng)計多個列的指標

  # res = users.groupby(by='ORGANIZE_NAME')[['age','USER_ID']].mean()

  res = users.groupby(by=['ORGANIZE_NAME', 'poo', 'sex'])['age'].mean()

  print(res)

  # 利用agg

  # 進行同時對age 求平均值、對userid 求最大值

  # 只需要指定 np.方法名

  print(users.agg({'age': np.mean, 'USER_ID': np.max}))

  # 對age 和 USER_ID 同時分別求 和 和均值

  print(users[['age', 'USER_ID']].agg([np.sum, np.mean]))

  # 對age USER_ID 求取不同個數(shù)的統(tǒng)計指標

  print(users.agg({'age': np.min, 'USER_ID': [np.mean, np.sum]}))

  def hh(x):

  return x + 1

  # 自定義函數(shù)進行計算

  # res = users['age'].apply(hh)

  # res = users[['age','USER_ID']].apply(lambda x:x+1)

  res = users['age'].transform(lambda x: x + 1)

  # 不能進行跨列的運算

  print(res)

  四、透視表與交叉表

  import pandas as pd

  # 加載數(shù)據(jù)

  detail = pd.read_excel("./meal_order_detail.xlsx")

  print("detail :\n", detail)

  print("detail 的列名:\n", detail.columns)

  print("detail 的數(shù)據(jù)類型:\n", detail.dtypes)

  # 獲取時間點的日屬性

  # 必須pandas默認支持的時間序列類型

  detail.loc[:, 'place_order_time'] = pd.to_datetime(detail.loc[:, 'place_order_time'])

  # 以列表推導(dǎo)式來獲取日屬性

  detail.loc[:, 'day'] = [i.day for i in detail.loc[:, 'place_order_time']]

  # 透視表 是一種plus 版的分組聚合

  # 創(chuàng)建一個透視表

  # data dataframe數(shù)據(jù)

  # values 最終統(tǒng)計指標所針對對象,要關(guān)心的數(shù)據(jù)主體

  # index --按照index 進行行分組

  # columns ---按照columns進行列分組

  # aggfunc ---對主體 進行什么指標的統(tǒng)計

  # res = pd.pivot_table(data=detail[['amounts','order_id','counts','dishes_name','day']],values='amounts',columns=['day','counts'],index=['order_id','dishes_name'],aggfunc='mean',margins=True)

  # # print(res)無錫人流醫(yī)院 http://www.wxbhnk120.com/

  # res.to_excel("./hh.xlsx")

  # 交叉表 mini版的透視表

  # 如果只傳index 與columns 統(tǒng)計這兩列的相對個數(shù)

  # res = pd.crosstab(index=detail['counts'],columns=detail['amounts'])

  # values 必須和aggfunc同時存在

  res = pd.crosstab(index=detail['order_id'],columns=detail['counts'],values=detail['amounts'],aggfunc='mean')

  print(res)

  五、案例

  1、營業(yè)額案例

  import pandas as pd

  # detail 有時間數(shù)據(jù)

  # 加載數(shù)據(jù)

  detail = pd.read_excel("./meal_order_detail.xlsx")

  print("detail :\n", detail)

  print("detail 的列名:\n", detail.columns)

  print("detail 的數(shù)據(jù)類型:\n", detail.dtypes)

  # 計算每個菜品的銷售額 ,增加到detail

  detail.loc[:, 'pay'] = detail.loc[:, 'counts'] * detail.loc[:, 'amounts']

  # print(detail)

  # 獲取時間點的日屬性

  # 必須pandas默認支持的時間序列類型

  detail.loc[:, 'place_order_time'] = pd.to_datetime(detail.loc[:, 'place_order_time'])

  # 以列表推導(dǎo)式來獲取日屬性

  detail.loc[:, 'day'] = [i.day for i in detail.loc[:, 'place_order_time']]

  # print(detail)

  # 以 日 為分組 ,統(tǒng)計pay的sum

  res = detail.groupby(by='day')['pay'].sum()

  print(res)

  # print(type(res))

  df = pd.DataFrame(res.values, columns=['monty'], index=res.index)

  print(df)

  print(type(df))

  2、連鎖超市案例

  import pandas as pd

  # 加載數(shù)據(jù)

  order = pd.read_csv("./order.csv", encoding='ansi')

  print("order:\n", order)

  print("order 的列索引:\n", order.columns)

  # 1、哪些類別的商品比較暢銷?

  # 剔除銷量 < 0 的數(shù)據(jù) (保留銷量 >0 的數(shù)據(jù))

  # 保存

  bool_id = order.loc[:, '銷量'] > 0

  data = order.loc[bool_id, :] # 剔除異常數(shù)據(jù)之后的正常數(shù)據(jù)

  print(data.shape)

  print("*" * 80)

  # 刪除異常

  # bool_id = order.loc[:,'銷量'] <= 0

  # index = order.loc[bool_id,:].index

  #

  # data = order.drop(labels=index,axis=0,inplace=False)

  # 按照類別進行分組,統(tǒng)計銷量的 和

  # 進行dataframe或者series的值排序

  # 如果series sort_values()直接按照seies的值進行排序

  # 如果df 那么需要指定 按照哪一列進行排序,by= 列名

  # 默認是升序ascending=True

  # ascending=False 降序

  # res = data.groupby(by='類別ID')['銷量'].sum().sort_values(ascending=False)

  #

  # print(res)

  # 2、哪些商品比較暢銷?

  # 分組聚合實現(xiàn)

  # res = data.groupby(by='商品ID')['銷量'].sum().sort_values(ascending=False).head(10)

  #

  # print(res)

  # 透視表實現(xiàn)

  # res = pd.pivot_table(data=data.loc[:, ['商品ID', '銷量']], index='商品ID', values='銷量', aggfunc='sum').sort_values(by='銷量',

  # ascending=False).head(

  # 10)

  # print(res)

  # 3、求不同門店的銷售額占比

  # 提示:訂單中沒有銷售額字段,所有需要新增一個銷售額字段。增加字段后按照門店編號進行分組,然后計算占比。

  # # 先計算銷售額

  # data.loc[:,'銷售額'] = data.loc[:,'單價'] * data.loc[:,'銷量']

  #

  # # 按照門店編號進行分組統(tǒng)計銷售額的sum

  # res = data.groupby(by='門店編號')['銷售額'].sum()

  # # print(res)

  # # 計算所有的銷售額總和

  # all_ = res.sum()

  #

  # # print(all_)

  # per_ = res / all_

  #

  # print("各個門店的銷售額占比為:\n",per_.apply(lambda x:format(x,".2%")))

  # a = 100.105

  # print("%.2f"%a)

  # print("{}%".format(2.0))

  # 匿名函數(shù)

  # print(lambda x:x+5) #

  #

  # def add(x):

  # # return x+5

  # 4、哪段時間段是超市的客流高峰期?

  # 提示:需要知道每個時間段對應(yīng)的客流量,但是訂單表中既有日期又有時間,我們需要從中提出小時數(shù),這里利用訂單ID去重計數(shù)代表客流量。

  # 先對訂單去重

  # subset 去重的那一列 的列名,可以是多列,多列的時候傳列表

  data.drop_duplicates(subset='訂單ID', inplace=True)

  # print(data.shape)

  # 按照小時分組對訂單ID進行統(tǒng)計數(shù)量

  # 將成交時間轉(zhuǎn)化為 pandas默認支持的時間序列類型

  data.loc[:, '成交時間'] = pd.to_datetime(data.loc[:, '成交時間'])

  # 獲取小時屬性,增加到data 中

  data.loc[:, 'hour'] = [i.hour for i in data.loc[:, '成交時間']]

  # print(data)

  # 按照hour 分組 統(tǒng)計 訂單ID數(shù)量

  res = data.groupby(by='hour')['訂單ID'].count().sort_values(ascending=False)

  print(res)


向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI