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

เขียนโปรแกรม Python ลบคอล럼น์ หนึ่งหรือหลายคอลัมน์ใน DataFrame

สมมติว่าคุณมี DataFrame และต้องการลบคอลัมน์ หนึ่งคอลัมน์ หรือหลายคอลัมน์พร้อมกัน

วิธีที่ 1: ใช้คำสั่ง del

import pandas as pd

data = [[1, 2, 3], [4, 5, 6]]
df = pd.DataFrame(data, columns=('one', 'two', 'three'))
print("ก่อนลบ:\n", df)

del df['one']
print("\nหลังลบคอลัมน์ 'one' ด้วย del:")
print(df)

ผลลัพธ์

ก่อนลบ:
   one  two  three
0    1    2      3
1    4    5      6

หลังลบคอลัมน์ 'one' ด้วย del:
   two  three
0    2      3
1    5      6

วิธีที่ 2: ใช้ pop()


df.pop('one')
print("\nหลังลบคอลัมน์ 'one' ด้วย pop():")
print(df)

ผลลัพธ์

หลังลบคอลัมน์ 'one' ด้วย pop():
   two  three
0    2      3
1    5      6

วิธีที่ 3: ใช้ drop() ลบหลายคอลัมน์พร้อมกัน


df.drop(columns=['one', 'two'], inplace=True)
print("\nหลังลบคอลัมน์ 'one' และ 'two' ด้วย drop():")
print(df)

ผลลัพธ์

หลังลบคอลัมน์ 'one' และ 'two' ด้วย drop():
   three
0      3
1      6

คำอธิบาย:

  • del df['col']: ลบคอลัมน์เดียว แบบ in-place ไม่คืนค่า
  • df.pop('col'): ลบคอลัมน์เดียว แบบ in-place คืนค่า Series ที่ลบไป (ใช้ได้ถ้าต้องการเก็บค่าไว้)
  • df.drop(columns=[...], inplace=True): ลบหลายคอลัมน์พร้อมกัน inplace=True แก้ไข DataFrame เดิม, inplace=False (default) คืนค่า DataFrame ใหม่
  • สามารถใช้ axis=1 แทน columns= ได้: df.drop(['one', 'two'], axis=1)