Giả sử bạn có một DataFrame và kết quả giá trị nhỏ thứ hai trong mỗi cột như sau:
Id 2 Salary 30000 Age 23
Để 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
- Định nghĩa một DataFrame
- Thiết lập df.apply() với lambda function truy xuất tất cả cột qua biến x, biểu thức x.sort_values().unique()[1], axis=0 để trả về giá trị nhỏ thứ hai
result = df.apply(lambda x: x.sort_values().unique()[1], axis=0)
Ví dụ
Hãy kiểm tra mã sau để hiểu rõ hơn:
import pandas as pd
df = pd.DataFrame({'Id': [1,2,3,4,5,6,7,8,9,10],
'Salary': [20000, 30000, 50000, 40000, 80000, 90000, 350000, 55000, 60000, 70000],
'Age': [22, 23, 24, 25, 26, 25, 26, 27, 25, 24]})
print("DataFrame is:\n", df)
print("Second lowest value of each column is:")
result = df.apply(lambda x: x.sort_values().unique()[1], axis=0)
print(result)
Đầu ra
DataFrame is: Id Salary Age 0 1 20000 22 1 2 30000 23 2 3 50000 24 3 4 40000 25 4 5 80000 26 5 6 90000 25 6 7 350000 26 7 8 55000 27 8 9 60000 25 9 10 70000 24 Second lowest value of each column is: Id 2 Salary 30000 Age 23 dtype: int64