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

เขียนโค้ด Python เพื่อหาค่าที่น้อยที่สุดอันดับสองในแต่ละคอลัมน์ของ DataFrame ที่กำหนด


สมมติว่าคุณมี DataFrame และผลลัพธ์ของค่าที่น้อยที่สุดอันดับสองในแต่ละคอลัมน์มีดังนี้:

Id       2
Salary   30000
Age      23

ในการแก้ปัญหานี้ เราจะทำตามขั้นตอนดังนี้:

วิธีแก้ปัญหา

  • กำหนด DataFrame

  • ใช้ df.apply() พร้อม lambda function ตั้งตัวแปร x เพื่อเข้าถึงทุกคอลัมน์ และตรวจสอบนิพจน์ x.sort_values().unique()[1] กับ axis=0 เพื่อคืนค่าที่น้อยที่สุดอันดับสอง ดังนี้:

result = df.apply(lambda x: x.sort_values().unique()[1], axis=0)

ตัวอย่าง

ลองดูโค้ดต่อไปนี้เพื่อเข้าใจได้ดียิ่งขึ้น:

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)

ผลลัพธ์

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