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

วิธีใช้ฟังก์ชันแบบ element-wise กับ DataFrame ใน Python

เมื่อต้องใช้ฟังก์ชันกับทุกเซลล์ใน DataFrame แบบไม่สามารถ vectorize ได้ ให้ใช้ applymap ซึ่งรับค่าเดี่ยว คืนค่าเดี่ยว

ตัวอย่าง

import pandas as pd
import numpy as np

my_df = pd.DataFrame(np.random.randn(5,5), columns=['col_1','col_2','col_3','col_4','col_5'])
print("DataFrame ต้นฉบับ:")
print(my_df)

# คูณทุกค่าด้วย 11.45
my_df.applymap(lambda x: x * 11.45)
print("\nหลัง applymap:")
print(my_df.apply(np.mean))

ผลลัพธ์

DataFrame ต้นฉบับ:
       col_1     col_2     col_3     col_4     col_5
0 -0.671510 -0.860741  0.886484  0.842158  2.182341
1 -1.355763  0.247240 -0.653630 -0.278095  0.163044
2 -0.816203  1.664006  1.555648  1.625890 -0.412338
3 -1.013273 -1.565076  1.297014 -0.303504 -1.623573
4  0.725949 -0.077588 -0.886957  0.433478 -0.300151

หลัง applymap:
col_1   -0.626160
col_2   -0.118432
col_3    0.439712
col_4    0.463985
col_5    0.001865
dtype: float64

คำอธิบาย

  • นำเข้าไลบรารี pandas และ numpy
  • สร้าง DataFrame 5x5 จากข้อมูลสุ่ม
  • ใช้ applymap กับ lambda function คูณ 11.45
  • แสดงค่าเฉลี่ยแต่ละคอลัมน์ด้วย apply(np.mean)