การใช้ Lambda Function กับแต่ละแถว
ตัวอย่างโค้ด
import pandas as pd
df = pd.DataFrame([(10, 3, 13), (0, 42, 11), (26, 52, 1)], columns=list('xyz'))
print("เมทริกซ์เดิม")
print(df)
NewMatrix = df.apply(lambda a: a + 10, axis=1)
print("เมทริกซ์ที่แก้ไขแล้ว")
print(NewMatrix)
ผลลัพธ์
การรันโค้ดข้างต้นจะได้ผลลัพธ์ดังนี้ -
เมทริกซ์เดิม
x y z
0 10 3 13
1 0 42 11
2 26 52 1
เมทริกซ์ที่แก้ไขแล้ว
x y z
0 20 13 23
1 10 52 21
2 36 62 11
การใช้ User Defined Function
ตัวอย่างโค้ด
import pandas as pd
def SquareData(x):
return x * x
df = pd.DataFrame([(10, 3, 13), (0, 42, 11), (26, 52, 1)], columns=list('xyz'))
print("เมทริกซ์เดิม")
print(df)
NewMatrix = df.apply(SquareData, axis=1)
print("เมทริกซ์ที่แก้ไขแล้ว")
print(NewMatrix)
ผลลัพธ์
การรันโค้ดข้างต้นจะได้ผลลัพธ์ดังนี้ -
เมทริกซ์เดิม
x y z
0 10 3 13
1 0 42 11
2 26 52 1
เมทริกซ์ที่แก้ไขแล้ว
x y z
0 100 9 169
1 0 1764 121
2 676 2704 1