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

วิธีหาค่าเฉลี่ย (Mean) ของ Column เฉพาะใน DataFrame Pandas Python

Mean (ค่าเฉลี่ยเลขคณิต) = ผลรวมค่าทั้งหมด / จำนวนค่า ใช้สรุป Central Tendency ของข้อมูล

ใน Pandas ใช้ Method .mean() บน Series หรือ DataFrame

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


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)

# Mean ของ Column 'Age'
print("\nThe mean of column 'Age' is:")
print(my_df['Age'].mean())

# Mean ของ Column 'value'
print("\nThe mean of column 'value' is:")
print(my_df['value'].mean())

# Mean ทุก Numeric Columns
print("\nMean of all numeric columns:")
print(my_df.mean())

ผลลัพธ์


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 mean of column 'Age' is:
47.2

The mean of column 'value' is:
46.553999999999995

Mean of all numeric columns:
Age     47.200000
value   46.554000
dtype: float64

คำอธิบาย

  • เข้าถึง Column เดี่ยว: my_df['Age'].mean()

  • ทั้ง DataFrame: my_df.mean() (เฉพาะ Numeric Columns)

  • Column 'Name' (String) จะถูกข้ามอัตโนมัติ

พารามิเตอร์ mean()


Series.mean(axis=0, skipna=True, numeric_only=False)
  • skipna=True: ข้าม NaN (Default)
  • numeric_only: DataFrame เท่านั้น

Weighted Mean (ค่าเฉลี่ยน้ำหนัก)


# Manual weighted mean
weights = pd.Series([0.1, 0.2, 0.3, 0.2, 0.2], index=my_df.index)
weighted_mean = (my_df['value'] * weights).sum() / weights.sum()
print(f"Weighted mean: {weighted_mean:.4f}")

# หรือใช้ numpy.average
import numpy as np
print(np.average(my_df['value'], weights=weights))

Trimmed Mean (ตัดค่านอกขอบ)


from scipy import stats
# ตัด 10% ด้านบน-ล่าง
trimmed = stats.trim_mean(my_df['value'], 0.1)
print(f"Trimmed mean (10%): {trimmed:.4f}")

การจัดการ Missing Values


df_with_nan = pd.Series([1, 2, np.nan, 4, 5])
print(df_with_nan.mean())        # 3.0 (skipna=True default)
print(df_with_nan.mean(skipna=False))  # NaN