簡體   English   中英

將 Pandas pivot_table function 轉換為 Polars pivot Function

[英]Convert Pandas pivot_table function into Polars pivot Function

我正在嘗試將一些 python pandas 轉換為極坐標。 我一直在嘗試將 pandas pivot_table function 轉換為極坐標。 以下是有效的 pandas 代碼。 I can't seem to get the same behavior with the Polars pivot function. The polars pivot function forces the column parameter and uses the column values as headers instead of the column label as a header. I'm going for the same output below but使用 Polars 而不是 Pandas。

df = pd.DataFrame({"obj" : ["ring", "shoe", "ring"], "price":["65", "42", "65"], "value":["53", "55", "54"], "date":["2022-02-07", "2022-01-07", "2022-03-07"]})

table = pd.pivot_table(df, values=['price','value','date'],index=['obj'], aggfunc={'price': pd.Series.nunique,'value':pd.Series.nunique,'date':pd.Series.nunique})

print(table)

輸出如下:

        date    price     value  
obj  
ring    2       1         2  
shoe    1       1         1

在 Polars 中,我們不會為此使用 pivot 表。 相反,我們會使用groupbyagg函數。 使用您的數據,它將是:

import polars as pl
df = pl.from_pandas(df)

df.groupby("obj").agg(pl.all().n_unique())
shape: (2, 4)
┌──────┬───────┬───────┬──────┐
│ obj  ┆ price ┆ value ┆ date │
│ ---  ┆ ---   ┆ ---   ┆ ---  │
│ str  ┆ u32   ┆ u32   ┆ u32  │
╞══════╪═══════╪═══════╪══════╡
│ ring ┆ 1     ┆ 2     ┆ 2    │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌┤
│ shoe ┆ 1     ┆ 1     ┆ 1    │
└──────┴───────┴───────┴──────┘

pivot 和融

我們在 Polars 中使用pivot function 的地方是將“長”格式的數據集匯總為“寬”格式的數據集。 例如,讓我們使用melt function 將原始數據集轉換為“長”格式。

df2 = df.melt(id_vars="obj", value_vars=["price", "date", "value"])
print(df2)
shape: (9, 3)
┌──────┬──────────┬────────────┐
│ obj  ┆ variable ┆ value      │
│ ---  ┆ ---      ┆ ---        │
│ str  ┆ str      ┆ str        │
╞══════╪══════════╪════════════╡
│ ring ┆ price    ┆ 65         │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤
│ shoe ┆ price    ┆ 42         │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤
│ ring ┆ price    ┆ 65         │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤
│ ring ┆ date     ┆ 2022-02-07 │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤
│ shoe ┆ date     ┆ 2022-01-07 │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤
│ ring ┆ date     ┆ 2022-03-07 │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤
│ ring ┆ value    ┆ 53         │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤
│ shoe ┆ value    ┆ 55         │
├╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤
│ ring ┆ value    ┆ 54         │
└──────┴──────────┴────────────┘

現在讓我們使用pivot將這個“長”格式的數據集總結回“寬”格式的數據集,並簡單地計算值的數量。

df2.pivot(values='value', index='obj', columns='variable', aggregate_fn='count')
shape: (2, 4)
┌──────┬──────┬───────┬───────┐
│ obj  ┆ date ┆ price ┆ value │
│ ---  ┆ ---  ┆ ---   ┆ ---   │
│ str  ┆ u32  ┆ u32   ┆ u32   │
╞══════╪══════╪═══════╪═══════╡
│ ring ┆ 2    ┆ 2     ┆ 2     │
├╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┤
│ shoe ┆ 1    ┆ 1     ┆ 1     │
└──────┴──────┴───────┴───────┘

這是否有助於闡明pivot功能的使用?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM