如何在 Pandas 中檢查一個列是否存在?
為了檢查 Pandas DataFrame 中是否存在一個列,我們可以按照以下步驟操作 −
步驟
建立一個二維、大小可變、潛在的異構表格資料,**df**。
列印輸入 DataFrame,**df**。
使用列名初始化一個**col**變數。
建立一個使用者自定義函式**check()**來檢查 DataFrame 中是否存在一個列。
使用有效的列名呼叫**check()**方法。
使用無效的列名呼叫**check()**方法。
示例
import pandas as pd
def check(col):
if col in df:
print "Column", col, "exists in the DataFrame."
else:
print "Column", col, "does not exist in the DataFrame."
df = pd.DataFrame(
{
"x": [5, 2, 1, 9],
"y": [4, 1, 5, 10],
"z": [4, 1, 5, 0]
}
)
print "Input DataFrame is:
", df
col = "x"
check(col)
col = "a"
check(col)輸出
Input DataFrame is: x y z 0 5 4 4 1 2 1 1 2 1 5 5 3 9 10 0 Column x exists in the DataFrame. Column a does not exist in the DataFrame.
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP