新手向——理解Pandas的Transform

Understanding the Transform Function in Pandas

  • Pandas具有豐富的功能讓我們探索,transform就是其中之一,利用它可以高效地匯總數(shù)據(jù)。
  • Python Data Science Handbook 是一個(gè)關(guān)于pandas的優(yōu)秀資源。
  • 在該書的描述中,transform是與groupby(pandas中最有用的操作之一)組合使用的。一般情況下,我們在groupby之后使用aggregate , filter 或 apply來匯總數(shù)據(jù),transform可能稍難理解。
  • 該書對應(yīng)的github資源 jupyter notebooks里的內(nèi)容可能對理解transform的獨(dú)特作用有所幫助。

aggregation會(huì)返回?cái)?shù)據(jù)的縮減版本,而transformation能返回完整數(shù)據(jù)的某一變換版本供我們重組。這樣的transformation,輸出的形狀和輸入一致。一個(gè)常見的例子是通過減去分組平均值來居中數(shù)據(jù)。

實(shí)踐

  • 加載數(shù)據(jù)
import pandas as pd

df = pd.read_excel("sales_transactions.xlsx")
  • 查看數(shù)據(jù)
  • 可以看到數(shù)據(jù)包含了不同的訂單(order),以及訂單里的不同商品的數(shù)量(quantity)、單價(jià)(unit price)和總價(jià)(ext price)
  • 現(xiàn)在我們的任務(wù)是為數(shù)據(jù)表添加一列,表示不同商品在所在訂單的價(jià)錢占比。
  • 首先我們要獲得每個(gè)訂單的總花費(fèi)。groupby可以實(shí)現(xiàn)。
df.groupby('order')["ext price"].sum()
order
10001     576.12
10005    8185.49
10006    3724.49
Name: ext price, dtype: float64
  • 這些新得到的數(shù)據(jù)如何與原始數(shù)據(jù)幀結(jié)合呢?
order_total = df.groupby('order')["ext price"].sum().rename("Order_Total").reset_index()

df_1 = df.merge(order_total)
df_1["Percent_of_Order"] = df_1["ext price"] / df_1["Order_Total"]

  • 我們實(shí)現(xiàn)了目標(biāo)(還多加了一列訂單總額),但是步驟比較多,有沒有更好的辦法呢?——主角出場:)

Transform

  • 我們先試下
df.groupby('order')["ext price"].transform('sum')
0      576.12
1      576.12
2      576.12
3     8185.49
4     8185.49
5     8185.49
6     8185.49
7     8185.49
8     3724.49
9     3724.49
10    3724.49
11    3724.49
dtype: float64
  • 不再是只顯示3個(gè)訂單的對應(yīng)項(xiàng),而是保持了與原始數(shù)據(jù)集相同數(shù)量的項(xiàng)目,這樣就很好繼續(xù)了。這就是transform的獨(dú)特之處。
df["Order_Total"] = df.groupby('order')["ext price"].transform('sum')
df["Percent_of_Order"] = df["ext price"] / df["Order_Total"]
  • 甚至可以一步:
df["Percent_of_Order"] = df["ext price"] / df.groupby('order')["ext price"].transform('sum')
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容