Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python Pandas – คำนวณ Last Value ของแต่ละ Group (GroupBy Last)

ภาพรวม

ใช้ groupby().last() หาค่าแถวสุดท้ายของแต่ละกลุ่ม (ตามลำดับใน DataFrame)

ตัวอย่างโค้ด


import pandas as pd

dataFrame = pd.DataFrame({
    "Car": ['BMW', 'Lexus', 'BMW', 'Tesla', 'Lexus', 'Tesla'],
    "Place": ['Delhi', 'Bangalore', 'Pune', 'Punjab', 'Chandigarh', 'Mumbai'],
    "Units": [100, 150, 50, 80, 110, 90]
})

print("DataFrame ...\n", dataFrame)

groupDF = dataFrame.groupby("Car")
res = groupDF.last().reset_index()

print("\nLast of group values =\n", res)

ผลลัพธ์

DataFrame ...
     Car       Place  Units
0    BMW      Delhi    100
1  Lexus  Bangalore    150
2    BMW      Pune      50
3  Tesla    Punjab      80
4  Lexus Chandigarh    110
5  Tesla    Mumbai      90

Last of group values =
     Car       Place  Units
0    BMW      Pune      50
1  Lexus Chandigarh    110
2  Tesla    Mumbai      90

คำอธิบาย

  • BMW: แถว index 2 (Pune, 50) เป็น last occurrence
  • Lexus: แถว index 4 (Chandigarh, 110)
  • Tesla: แถว index 5 (Mumbai, 90)
  • reset_index() ทำให้กลับเป็น DataFrame ปกติ (Car กลายเป็นคอลัมน์)

ฟังก์ชัน GroupBy อื่นๆ

การจัดเรียงก่อน GroupBy (สำคัญ!)

last() ขึ้นอยู่กับลำดับแถวใน DataFrame หากต้องการ last ตามเวลา ต้อง sort ก่อน:


df = df.sort_values('Date_of_Purchase').groupby('Car').last()
Methodคำอธิบาย
first()แถวแรกของแต่ละกลุ่ม
last()แถวสุดท้ายของแต่ละกลุ่ม
nth(n)แถวที่ n (0-based) ของแต่ละกลุ่ม
head(n)n แถวแรก
tail(n)n แถวสุดท้าย