我有一個巨大的 excel 檔案,如下所示:
表 1
我的愿望表是這樣的:
我的 dsire 表
我使用 group by、count 和 sum 如下:
import pandas as pd
import openpyxl as op
from openpyxl import load_workbook
from openpyxl import Workbook
import numpy as np
path1 = r"users.xlsx"
data = pd.read_excel(path1, engine='openpyxl')
df = pd.DataFrame(data)
NumberOfChild = df.groupby('Parent ID')['Parent ID'].count().to_frame('Employees Number')
NumberOfBooking = df.groupby('Parent ID')['Reservations Count'].transform('sum')
這給了我正確數量的 Booking 和 Child,但我不能在 numberOfChild 和 numberOfBooking 列中獲得這些值
uj5u.com熱心網友回復:
假設您有以下資料框
>>> df
id parent_id reservations
0 1 NaN 1
1 2 1.0 3
2 3 1.0 5
3 4 NaN 2
4 5 4.0 6
5 6 NaN 7
首先計算孩子的數量
>>> children = df.groupby("parent_id").id.count().rename("children")
>>> children
parent_id
1.0 2
4.0 1
Name: children, dtype: int64
然后創建一個聚合一個新列,如果該行沒有 parent_id,則該列將是 id,否則為 parent_id
>>> df["book_key"] = df.parent_id.fillna(df.id).astype(int)
>>> df
id parent_id reservations book_key
0 1 NaN 1 1
1 2 1.0 3 1
2 3 1.0 5 1
3 4 NaN 2 4
4 5 4.0 6 4
5 6 NaN 7 6
使用這個新鍵來計算預訂總數
>>> reservations = df.groupby("book_key").reservations.sum().rename("total")
>>> reservations
book_key
1 9
4 8
6 7
Name: total, dtype: int64
最后加入資料框,洗掉 book_key 列并可選地將 NaN 替換為 ""
>>> df = df.set_index("id").join(children).join(reservations).drop(columns="book_key").fillna("")
>>> df
parent_id reservations children total
id
1 1 2.0 9.0
2 1.0 3
3 1.0 5
4 2 1.0 8.0
5 4.0 6
6 7 7.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/345599.html
標籤:Python 蟒蛇-3.x 熊猫 pandas-groupby
下一篇:字典分組按鍵的子串
