ผลลัพธ์ของการสร้าง DataFrame และคำนวณค่าสูงสุดหารค่าต่ำสุดของแต่ละแถวมีดังนี้:
0 43.000000 1 1.911111 2 2.405405 3 20.000000 4 7.727273 5 6.333333
ในการแก้ปัญหานี้ เราจะทำตามขั้นตอนดังนี้:
วิธีที่ 1
กำหนด DataFrame ด้วยขนาด 30 องค์ประกอบสุ่มจาก 1 ถึง 100 และ reshape อาร์เรย์เป็น (6,5) เพื่อเปลี่ยนเป็นอาร์เรย์ 2 มิติ
df = pd.DataFrame(np.random.randint(1, 100, 30).reshape(6, 5))
สร้างฟังก์ชัน df.apply ภายใน lambda method เพื่อคำนวณ np.max(x)/np.min(x) กับ axis=1 และเก็บเป็น max_of_min ดังนี้:
max_of_min = df.apply(lambda x: np.max(x)/np.min(x), axis=1)
สุดท้าย พิมพ์ max_of_min
ตัวอย่าง
ลองดูโค้ดต่อไปนี้เพื่อเข้าใจได้ดียิ่งขึ้น:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(1, 100, 30).reshape(6, 5))
print("Dataframe is:\n", df)
max_of_min = df.apply(lambda x: np.max(x)/np.min(x), axis=1)
print("maximum by minimum of each row:\n", max_of_min)
ผลลัพธ์
Dataframe is: 0 1 2 3 4 0 2 13 4 15 86 1 60 53 86 75 45 2 37 85 40 89 88 3 67 33 80 4 74 4 85 71 11 67 81 5 56 85 95 15 94 maximum by minimum of each row: 0 43.000000 1 1.911111 2 2.405405 3 20.000000 4 7.727273 5 6.333333 dtype: float64