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

การลบ Column ใน DataFrame ด้วย pop() ใน Pandas Python

Method .pop() ลบ Column จาก DataFrame **และคืนค่า Column ที่ลบออกเป็น Series** เหมือน Dictionary.pop()

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


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' ด้วย pop()
popped_column = my_df.pop('cd')
print("\nPopped column 'cd':")
print(popped_column)

print("\nDataFrame after pop:")
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

Popped column 'cd':
a    1
b    2
c    0
d    9
Name: cd, dtype: int64

DataFrame after pop:
    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

คำอธิบาย

  • สร้าง DataFrame 4 Columns (ab, cd, ef, gh)

  • popped = my_df.pop('cd') - ลบ Column 'cd' และเก็บค่าที่ลบไว้ในตัวแปร

  • DataFrame เหลือ 3 Columns (ab, ef, gh)

เปรียบเทียบวิธีลบ Column

MethodSyntaxReturn ValueIn-placeMultiple Columns
popdf.pop('col')Series (Column ที่ลบ)YesNo (ทีละ Column)
deldel df['col']NoneYesNo
dropdf.drop('col', axis=1)DataFrame ใหม่ (Default)No (ต้อง inplace=True)Yes (List)

ตัวอย่าง drop() - ลบหลาย Column พร้อมกัน


# ลบหลาย Column (คืน DataFrame ใหม่)
df_new = df.drop(['col1', 'col2'], axis=1)

# ลบ In-place
df.drop(['col1', 'col2'], axis=1, inplace=True)

# ลบด้วย Index Position
df.drop(df.columns[[0, 2]], axis=1, inplace=True)

Error Handling


# pop() จะ Raise KeyError ถ้า Column ไม่มี
try:
    df.pop('nonexistent')
except KeyError:
    print("Column not found")

# drop() มี errors parameter
df.drop('nonexistent', axis=1, errors='ignore')  # ไม่ Error

เมื่อไหร่ใช้ pop()? ต้องการใช้ Column ที่ลบออกต่อ (เช่นย้ายไป DataFrame อื่น, คำนวณแล้วทิ้ง)