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

การใช้ apply() Row-wise และ Column-wise บน DataFrame ใน Pandas

ฟังก์ชัน apply() ใน DataFrame ใช้เรียกฟังก์ชันตาม Axis ที่กำหนด:

  • axis=0 (Default): Column-wise - ส่งแต่ละ Column (Series) ให้ฟังก์ชัน
  • axis=1: Row-wise - ส่งแต่ละ Row (Series) ให้ฟังก์ชัน

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


import pandas as pd
import numpy as np

my_data = {
    '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)

# Column-wise: คำนวณ Mean แต่ละ Column
print("\nColumn means (axis=0 default):")
print(my_df.apply(np.mean))

# Row-wise: คำนวณ Mean แต่ละ Row
print("\nRow means (axis=1):")
print(my_df.apply(np.mean, axis=1))

# Row-wise: ฟังก์ชันกำหนดเอง
def row_range(row):
    return row.max() - row.min()

print("\nRow range (max - min):")
print(my_df.apply(row_range, axis=1))

ผลลัพธ์


The dataframe is:
   Age  value
0  45   8.79
1  67  23.24
2  89  31.98
3  12  78.56
4  23  90.20

Column means (axis=0 default):
Age     47.200
value   46.554
dtype: float64

Row means (axis=1):
0    26.895
1    45.120
2    60.490
3    45.280
4    56.600
dtype: float64

Row range (max - min):
0    36.21
1    43.76
2    57.02
3    66.56
4    67.20
dtype: float64

คำอธิบาย

  • สร้าง DataFrame จาก Dictionary of Series

  • apply(np.mean) / apply(np.mean, axis=0) - Column-wise Mean

  • apply(np.mean, axis=1) - Row-wise Mean

  • apply(custom_func, axis=1) - Row-wise Custom Function

เมื่อไหร่ควรใช้ apply()?

  • ฟังก์ชันที่ไม่สามารถ Vectorize ได้ (Complex Logic, Multiple Columns)
  • Row-wise Operations ที่ต้องเข้าถึงหลาย Column พร้อมกัน
  • ใช้กับ Built-in Functions (np.mean, np.sum, etc.) ได้แต่ Vectorized เร็วกว่า

ตัวอย่าง Row-wise ที่ใช้จริง


# สร้าง Column ใหม่จากเงื่อนไขหลาย Column
df['status'] = df.apply(
    lambda row: 'Senior' if row['Age'] > 60 else 'Junior', axis=1
)

# คำนวณ Weighted Score
df['score'] = df.apply(
    lambda row: 0.3*row['math'] + 0.7*row['english'], axis=1
)

ประสิทธิภาพ: apply(axis=1) ช้า สำหรับ DataFrame ใหญ่ ควรพิจารณา Vectorization, np.where, eval(), หรือ numba