開始使用免費開始

從 DataFrame 刪除欄位

有時候你的 DataFrame 會包含不再需要的欄位。為了讓資料更精簡,你常常需要移除一些欄位。你還記得在影片中要用哪個方法來刪除列或欄嗎?

假設你想把 PCE 計算結果呈現給公司內部利害關係人,但不想顯示用來計算的那些欄位。請從提供的 DataFrame pce 中刪除欄位 PCDGPCNDPCESV,只保留欄位 PCE。已提供清單 columns_to_drop

本練習屬於課程

Intermediate Python for Finance

檢視課程

練習說明

  • 列印 pce DataFrame 的欄位。
  • 建立一個新的 DataFrame,其來源為 pce,但排除清單 columns_to_drop 中的欄位。
  • 列印新 DataFrame 的欄位。
  • 就地(in place)從 DataFrame pce 中刪除 columns_to_drop 的欄位。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

columns_to_drop = ['PCDG', 'PCND', 'PCESV']

# Print the current columns of the DataFrame pce
____(pce.columns)

# Create new_pce by dropping columns_to_drop from pce
new_pce = pce.drop(columns=____)
# Print the columns of the new DataFrame
print(new_pce.____)

# Drop the columns in_place in the original DataFrame
pce.____(columns=columns_to_drop, inplace=____)

# Print the columns of the DataFrame pce
print(pce.columns)
編輯並執行程式碼