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

Python Pandas – หาค่าที่ไม่ซ้ำจากหลายคอลัมน์


เพื่อหาค่าที่ไม่ซ้ำจากหลายคอลัมน์ ใช้เมธอด unique() สมมติว่าคุณมีบันทึกพนักงานพร้อม "EmpName" และ "Zone" ใน Pandas DataFrame ชื่อและโซนอาจซ้ำได้ เนื่องจากพนักงานสองคนอาจมีชื่อเหมือนกัน และโซนหนึ่งอาจมีพนักงานมากกว่าหนึ่งคน ในกรณีนั้น หากต้องการชื่อพนักงานที่ไม่ซ้ำ ให้ใช้ unique() สำหรับ DataFrame

ก่อนอื่น import ไลบรารีที่จำเป็น ตั้ง pd เป็นอีเลียส -

import pandas as pd

ก่อนอื่น สร้าง DataFrame ที่นี่มีสองคอลัมน์ -

dataFrame = pd.DataFrame(
    {
        "EmpName": ['John', 'Ted', 'Jacob', 'Scarlett', 'Ami', 'Ted', 'Scarlett'],
        "Zone": ['North', 'South', 'South', 'East', 'West', 'East', 'North']
    }
)

ดึงชื่อพนักงานที่ไม่ซ้ำและโซนจากคอลัมน์ "EmpName" และ "Zone" ของ DataFrame -

{pd.concat([dataFrame['EmpName'], dataFrame['Zone']]).unique()}

ตัวอย่าง

โค้ดสมบูรณ์ -

import pandas as pd
# Create DataFrame
dataFrame = pd.DataFrame(
    {
        "EmpName": ['John', 'Ted', 'Jacob', 'Scarlett', 'Ami', 'Ted', 'Scarlett'],
        "Zone": ['North', 'South', 'South', 'East', 'West', 'East', 'North']
    }
)
print("DataFrame ...\n", dataFrame)
# Fetch unique values from multiple columns
print(f"\nFetching unique Values from the two columns and concatenate them:\n {pd.concat([dataFrame['EmpName'], dataFrame['Zone']]).unique()}")

ผลลัพธ์

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

DataFrame ...
   EmpName  Zone
0    John  North
1     Ted  South
2   Jacob  South
3 Scarlett  East
4     Ami  West
5     Ted  East
6 Scarlett  North
Fetching unique Values from the two columns and concatenate them:
['John' 'Ted' 'Jacob' 'Scarlett' 'Ami' 'North' 'South' 'East' 'West']