[英]Pandas - Selecting over multiple columns
您必須以一種或另一種方式指定您的條件。 您可以為每種情況創建單獨的蒙版,最終將其減少為單個蒙版:
import seaborn.apionly as sns
import operator
import numpy as np
# Load a sample dataframe to play with
df = sns.load_dataset('iris')
# Define individual conditions as tuples
# ([column], [compare_function], [compare_value])
cond1 = ('sepal_length', operator.gt, 5)
cond2 = ('sepal_width', operator.lt, 2)
cond3 = ('species', operator.eq, 'virginica')
conditions = [cond1, cond2, cond3]
# Apply those conditions on the df, creating a list of 3 masks
masks = [fn(df[var], val) for var, fn, val in conditions]
# Reduce those 3 masks to one using logical OR
mask = np.logical_or.reduce(masks)
result = df.ix[mask]
當我們將其與“手工制作”選項進行比較時,我們發現它們是相同的:
result_manual = df[(df.sepal_length>5) | (df.sepal_width<2) | (df.species == 'virginica')]
result_manual.equals(result) # == True
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.