วิธีคำนวณเปอร์เซ็นต์สะสมในหมีแพนด้า
คุณสามารถใช้ไวยากรณ์พื้นฐานต่อไปนี้เพื่อคำนวณเปอร์เซ็นต์สะสมของค่าในคอลัมน์ของ DataFrame ของแพนด้า:
#calculate cumulative sum of column df[' cum_sum '] = df[' col1 ']. cumsum () #calculate cumulative percentage of column (rounded to 2 decimal places) df[' cum_percent '] = round( 100 *df. cum_sum /df[' col1 ']. sum (), 2 )
ตัวอย่างต่อไปนี้แสดงวิธีใช้ไวยากรณ์นี้ในทางปฏิบัติ
ตัวอย่าง: คำนวณเปอร์เซ็นต์สะสมของหมีแพนด้า
สมมติว่าเรามี DataFrame แพนด้าต่อไปนี้ซึ่งแสดงจำนวนหน่วยที่บริษัทขายในปีติดต่อกัน:
import pandas as pd #createDataFrame df = pd. DataFrame ({' year ': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], ' units_sold ': [60, 75, 77, 87, 104, 134, 120, 125, 140, 150]}) #view DataFrame print (df) year units_sold 0 1 60 1 2 75 2 3 77 3 4 87 4 5 104 5 6 134 6 7 120 7 8 125 8 9 140 9 10 150
ต่อไป เราสามารถใช้โค้ดต่อไปนี้เพื่อเพิ่มคอลัมน์ที่แสดงจำนวนหน่วยที่ขายสะสมและเปอร์เซ็นต์สะสมของหน่วยที่ขายได้:
#calculate cumulative sum of units sold
df[' cum_sum '] = df[' units_sold ']. cumsum ()
#calculate cumulative percentage of units sold
df[' cum_percent '] = round( 100 *df. cum_sum /df[' units_sold ']. sum (), 2 )
#view updated DataFrame
print (df)
year units_sold cum_sum cum_percent
0 1 60 60 5.60
1 2 75 135 12.59
2 3 77 212 19.78
3 4 87 299 27.89
4 5 104 403 37.59
5 6 134 537 50.09
6 7 120 657 61.29
7 8 125 782 72.95
8 9 140 922 86.01
9 10 150 1072 100.00
เราตีความเปอร์เซ็นต์สะสมดังนี้:
- 5.60% ของยอดขายทั้งหมดเกิดขึ้นในปีแรก
- 12.59 ของยอดขายทั้งหมดเกิดขึ้นในปีที่ 1 และ 2 รวมกัน
- 19.78% ของยอดขายทั้งหมดเกิดขึ้นในปีที่ 1, 2 และ 3 รวมกัน
และอื่นๆ
โปรดทราบว่าคุณสามารถเปลี่ยนค่าในฟังก์ชัน round() เพื่อเปลี่ยนจำนวนจุดทศนิยมที่แสดงได้ด้วย
ตัวอย่างเช่น เราสามารถปัดเศษเปอร์เซ็นต์สะสมให้เป็นทศนิยมศูนย์แทนได้:
#calculate cumulative sum of units sold
df[' cum_sum '] = df[' units_sold ']. cumsum ()
#calculate cumulative percentage of units sold
df[' cum_percent '] = round( 100 *df. cum_sum /df[' units_sold ']. sum (), 0 )
#view updated DataFrame
print (df)
year units_sold cum_sum cum_percent
0 1 60 60 6.0
1 2 75 135 13.0
2 3 77 212 20.0
3 4 87 299 28.0
4 5 104 403 38.0
5 6 134 537 50.0
6 7 120 657 61.0
7 8 125 782 73.0
8 9 140 922 86.0
9 10 150 1072 100.0
เปอร์เซ็นต์สะสมจะถูกปัดเศษให้เป็นทศนิยมศูนย์
แหล่งข้อมูลเพิ่มเติม
บทช่วยสอนต่อไปนี้จะอธิบายวิธีดำเนินการทั่วไปอื่นๆ ใน Python:
วิธีสร้างตารางความถี่ใน Python
วิธีการคำนวณความถี่สัมพัทธ์ใน Python