使用複雜條件從 Pandas DataFrame 中進行篩選
我們可以使用不同的條件來比較 Pandas DataFrame 的所有列值。我們可以執行比較運算,如 df[col]<5, df[col]==10 等。例如,如果我們使用條件 df[col]>2,那麼它將檢查 col 中的所有值並比較它們是否大於 2。對於所有列值,如果條件成立,它將返回真,否則返回假。讓我們舉一個例子看看它是如何完成的。
步驟
- 建立一個二維、大小可變、潛在異構的表格資料,df。
- 列印輸入的資料框,df。
- 初始化一個變數 col,並指定一個列名。
- 執行一些比較運算。
- 列印結果資料框。
示例
import pandas as pd
df = pd.DataFrame(
{
"x": [5, 2, 7, 0],
"y": [4, 7, 5, 1],
"z": [9, 3, 5, 1]
}
)
print "Input DataFrame is:\n", df
col = "x"
print "Elements > 5 in column ", col, ":\n", df[col] > 5
print "Elements == 5 in column ", col, ":\n", df[col] == 5
col = "y"
print "Elements < 5 in column ", col, ":\n", df[col] < 5
print "Elements != 5 in column ", col, ":\n", df[col] != 5輸出
Input DataFrame is: x y z 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1 Elements > 5 in column x : 0 False 1 False 2 True 3 False Name: x, dtype: bool Elements == 5 in column x : 0 True 1 False 2 False 3 False Name: x, dtype: bool Elements < 5 in column y : 0 True 1 False 2 False 3 True Name: y, dtype: bool Elements != 5 in column y : 0 True 1 True 2 False 3 True Name: y, dtype: bool
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP