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

Python Pandas – ตรวจสอบว่าคอลัมน์เฉพาะของสอง DataFrame เท่ากันหรือไม่


เพื่อตรวจสอบว่าคอลัมน์เฉพาะของสอง DataFrame เท่ากันหรือไม่ ใช้เมธอด equals() มาสร้าง DataFrame1 ด้วยสองคอลัมน์ -

dataFrame1 = pd.DataFrame(
    {
        "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
        "Units": [100, 150, 110, 80, 110, 90]
    }
)

สร้าง DataFrame2 ด้วยสองคอลัมน์ -

dataFrame2 = pd.DataFrame(
    {
        "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Mercedes', 'Jaguar'],
        "Units": [100, 150, 110, 80, 110, 90]
    }
)

ตรวจสอบความเท่ากันของคอลัมน์ Units เฉพาะ -

dataFrame2['Units'].equals(dataFrame1['Units'])

ตัวอย่าง

โค้ดต่อไปนี้ -

import pandas as pd
# Create DataFrame1
dataFrame1 = pd.DataFrame(
    {
        "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
        "Units": [100, 150, 110, 80, 110, 90]
    }
)
print("DataFrame1 ...\n", dataFrame1)
# Create DataFrame2
dataFrame2 = pd.DataFrame(
    {
        "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
        "Units": [100, 150, 110, 80, 110, 90]
    }
)
print("\nDataFrame2 ...\n", dataFrame2)
# check for equality
print("\nAre both the DataFrame objects equal? ", dataFrame1.equals(dataFrame2))
# check for specific column Units equality
print("\nAre both the DataFrames have similar Units column? ", dataFrame2['Units'].equals(dataFrame1['Units']))

ผลลัพธ์

จะผลิตผลลัพธ์ดังนี้ -

DataFrame1 ...
    Car  Units
0   BMW    100
1  Lexus    150
2   Audi    110
3  Mustang    80
4 Bentley    110
5  Jaguar    90
DataFrame2 ...
    Car  Units
0   BMW    100
1  Lexus    150
2   Audi    110
3  Mustang    80
4 Bentley    110
5  Jaguar    90
Are both the DataFrame objects equal? True
Are both the DataFrames have similar Units column? True