Pandas: วิธีเปลี่ยนชื่อคอลัมน์ในฟังก์ชัน groupby
คุณสามารถใช้ไวยากรณ์พื้นฐานต่อไปนี้เพื่อเปลี่ยนชื่อคอลัมน์ในฟังก์ชัน groupby() ในหมีแพนด้า:
df. groupby (' group_col '). agg (sum_col1=(' col1 ', ' sum '), mean_col2=(' col2 ', ' mean '), max_col3=(' col3 ', ' max '))
ตัวอย่างนี้จะคำนวณคอลัมน์รวมสามคอลัมน์และตั้งชื่อเป็น sum_col1 , Mean_col2 และ max_col3
ตัวอย่างต่อไปนี้แสดงวิธีใช้ไวยากรณ์นี้ในทางปฏิบัติ
ตัวอย่าง: เปลี่ยนชื่อคอลัมน์ในฟังก์ชัน Groupby ใน Pandas
สมมติว่าเรามี DataFrame แพนด้าดังต่อไปนี้:
import pandas as pd #createDataFrame df = pd. DataFrame ({' team ': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'], ' points ': [30, 22, 19, 14, 14, 11, 20, 28], ' assists ': [5, 6, 6, 5, 8, 7, 7, 9], ' rebounds ': [4, 13, 15, 10, 7, 7, 5, 11]}) #view DataFrame print (df) team points assists rebounds 0 to 30 5 4 1 to 22 6 13 2 A 19 6 15 3 A 14 5 10 4 B 14 8 7 5 B 11 7 7 6 B 20 7 5 7 B 28 9 11
เราสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อจัดกลุ่มแถวตามคอลัมน์ ทีม จากนั้นคำนวณคอลัมน์รวมสามคอลัมน์พร้อมระบุชื่อเฉพาะสำหรับคอลัมน์รวม:
#calculate several aggregated columns by group and rename aggregated columns
df. groupby (' team '). agg (sum_points=(' points ', ' sum '),
mean_assists=(' assists ', ' mean '),
max_rebounds=(' rebounds ', ' max '))
sum_points mean_assists max_rebounds
team
A 85 5.50 15
B 73 7.75 11
โปรดทราบว่าคอลัมน์ที่รวบรวมไว้ทั้งสามคอลัมน์มีชื่อที่กำหนดเองที่เราระบุไว้ในฟังก์ชัน agg()
โปรดทราบว่าเราสามารถใช้ฟังก์ชัน NumPy เพื่อคำนวณผลรวม ค่าเฉลี่ย และค่าสูงสุดในฟังก์ชัน agg() ได้หากต้องการ
import numpy as np
#calculate several aggregated columns by group and rename aggregated columns
df. groupby (' team '). agg (sum_points=(' points ', np. sum ),
mean_assists=(' assists ', np. mean ),
max_rebounds=(' rebounds ', np. max ))
sum_points mean_assists max_rebounds
team
A 85 5.50 15
B 73 7.75 11
ผลลัพธ์เหล่านี้สอดคล้องกับผลลัพธ์ของตัวอย่างก่อนหน้านี้
แหล่งข้อมูลเพิ่มเติม
บทช่วยสอนต่อไปนี้จะอธิบายวิธีดำเนินการทั่วไปอื่น ๆ ในแพนด้า:
วิธีแสดงรายการชื่อคอลัมน์ทั้งหมดใน Pandas
วิธีจัดเรียงคอลัมน์ตามชื่อใน Pandas
วิธีลบคอลัมน์ที่ซ้ำกันใน Pandas