Kết quả tạo DataFrame và tính max chia min mỗi hàng:
0 43.000000 1 1.911111 2 2.405405 3 20.000000 4 7.727273 5 6.333333
Để giải quyết bài toán này, chúng ta sẽ làm theo các bước dưới đây:
Giải pháp 1
- Định nghĩa DataFrame với 30 phần tử ngẫu nhiên 1-100, reshape thành (6,5) thành mảng 2-D
df = pd.DataFrame(np.random.randint(1, 100, 30).reshape(6, 5))
- Tạo df.apply với lambda method tính np.max(x)/np.min(x), axis=1, lưu vào max_of_min
max_of_min = df.apply(lambda x: np.max(x) / np.min(x), axis=1)
- Cuối cùng in max_of_min
Ví dụ
Hãy kiểm tra mã sau để hiểu rõ hơn:
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)
Đầu ra
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