如何在 Python 中使用“pop”函式刪除資料框的一列?
資料框是一種二維資料結構,其中資料以表格格式儲存,以行和列的形式呈現。
它可以被視為 SQL 資料表或 Excel 表格的表示形式。可以使用不同的方法刪除資料框中的列。
我們將看到 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)
print("Deleting the column using the 'pop' function")
my_df.pop('cd')
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 Deleting the column using the 'pop' function 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
解釋
匯入所需的庫,併為方便使用提供別名。
建立包含鍵值對的字典,其中值實際上是 Series 資料結構。
此字典稍後作為引數傳遞給“pandas”庫中存在的“Dataframe”函式
“pop”函式用於刪除特定列。
需要刪除的列的名稱作為引數傳遞給“pop”函式。
新的資料框在控制檯上列印。
注意 - “NaN”指的是“非數字”,這意味著特定[行,列]值沒有任何有效條目。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP