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

การลบ Column ใน DataFrame ด้วย del Operator ใน Pandas Python

Keyword del ของ Python ใช้ลบ Column จาก DataFrame ได้โดยตรง (In-place) ไม่คืนค่าอะไร คล้ายการลบ Key จาก Dictionary

ตัวอย่างโค้ด


import pandas as pd

my_data = {
    'ab': pd.Series([1, 8, 7], index=['a', 'b', 'c']),
    'cd': pd.Series([1, 2, 0, 9], index=['a', 'b', 'c', 'd']),
    'ef': pd.Series([56, 78, 32], index=['a', 'b', 'c']),
    'gh': pd.Series([66, 77, 88, 99], index=['a', 'b', 'c', 'd'])
}

my_df = pd.DataFrame(my_data)
print("The dataframe is:")
print(my_df)

# ลบ Column 'cd' ด้วย del
del my_df['cd']

print("\nDataFrame after del:")
print(my_df)

ผลลัพธ์


The dataframe is:
    ab  cd   ef  gh
a  1.0   1  56.0  66
b  8.0   2  78.0  77
c  7.0   0  32.0  88
d  NaN   9  NaN   99

DataFrame after del:
    ab   ef  gh
a  1.0  56.0  66
b  8.0  78.0  77
c  7.0  32.0  88
d  NaN  NaN   99

คำอธิบาย

  • del my_df['cd'] ลบ Column 'cd' ทันที แบบ In-place

  • ไม่คืนค่า (ไม่สามารถเก็บ Column ที่ลบได้)

  • DataFrame เปลี่ยนแปลงโดยตรง

del vs pop() vs drop()

คุณสมบัติdelpop()drop()
คืนค่า Column ที่ลบไม่ใช่ (Series)ไม่ (Default), ใช่ (inplace=False)
In-placeใช่ใช่เฉพาะ inplace=True
ลบหลาย Columnไม่ (Loop ต้องทำเอง)ไม่ใช่ (List)
Error ถ้าไม่มี ColumnKeyErrorKeyErrorKeyError (errors='ignore' ป้องกันได้)

การลบหลาย Column ด้วย del (Loop)


cols_to_delete = ['cd', 'ef']
for col in cols_to_delete:
    if col in my_df.columns:
        del my_df[col]

การลบ Row (Index)


# ลบ Row ด้วย Index Label
del my_df.loc['a']        # Error: del ไม่รองรับ loc/iloc

# ใช้ drop แทน
my_df.drop('a', inplace=True)      # ลบ Row Index 'a'
my_df.drop([0, 1], inplace=True)   # ลบ Row Position 0, 1

สรุป: ใช้ del สำหรับลบ Column เดียวอย่างรวดเร็ว ไม่ต้องการค่าที่ลบ ใช้ pop() ถ้าต้องการค่า Column ใช้ drop() สำหรับหลาย Column หรือ Row