ใช้ Method .sum() บน Series (Column เดียว) หรือ DataFrame (ทุก Numeric Columns) เพื่อหาผลรวม
ตัวอย่างโค้ด
import pandas as pd
my_data = {
'Name': pd.Series(['Tom', 'Jane', 'Vin', 'Eve', 'Will']),
'Age': pd.Series([45, 67, 89, 12, 23]),
'value': pd.Series([8.79, 23.24, 31.98, 78.56, 90.20])
}
my_df = pd.DataFrame(my_data)
print("The dataframe is:")
print(my_df)
# Sum ของ Column 'Age' - โค้ดต้นฉบับใช้ my_df.sum(1) ซึ่งเป็น Row-wise Sum
# วิธีที่ถูกต้องสำหรับ Column 'Age':
print("\nThe sum of 'Age' column is:")
print(my_df['Age'].sum())
# Sum ของ Column 'value'
print("\nThe sum of 'value' column is:")
print(my_df['value'].sum())
# Sum ทุก Numeric Columns (Column-wise)
print("\nSum of all numeric columns (axis=0):")
print(my_df.sum())
# Row-wise Sum (Axis=1) - โค้ดต้นฉบับทำอย่างนี้
print("\nRow-wise sum (axis=1):")
print(my_df.sum(axis=1))
ผลลัพธ์
The dataframe is:
Name Age value
0 Tom 45 8.79
1 Jane 67 23.24
2 Vin 89 31.98
3 Eve 12 78.56
4 Will 23 90.20
The sum of 'Age' column is:
236
The sum of 'value' column is:
232.77
Sum of all numeric columns (axis=0):
Age 236.00
value 232.77
dtype: float64
Row-wise sum (axis=1):
0 53.79
1 90.24
2 120.98
3 90.56
4 113.20
dtype: float64
คำอธิบาย
my_df['Age'].sum()- Sum ของ Column 'Age' = 236my_df.sum()/my_df.sum(axis=0)- Column-wise Sum ทุก Numeric Columnsmy_df.sum(axis=1)- Row-wise Sum (ผลรวมแต่ละแถว)โค้ดต้นฉบับใช้
my_df.sum(1)ซึ่งเท่ากับaxis=1(Row-wise)
พารามิเตอร์ sum()
Series.sum(axis=0, skipna=True, numeric_only=False, min_count=0)
skipna=True: ข้าม NaN (Default)min_count: จำนวน Non-null ขั้นต่ำ (Default=0, ถ้าน้อยกว่าให้ NaN)
การใช้งานจริง
# Total Sales
total_sales = df['sales'].sum()
# Row Total (เช่น คะแนนรวมต่อคน)
df['total_score'] = df[['math', 'english', 'science']].sum(axis=1)
# Conditional Sum
high_value_sum = df.loc[df['value'] > 50, 'value'].sum()
# Groupby Sum
category_sum = df.groupby('category')['value'].sum()
Cumsum (Cumulative Sum)
# สะสมผลรวม
print(my_df['value'].cumsum())
# 0 8.79
# 1 32.03
# 2 64.01
# 3 142.57
# 4 232.77