熊猫-选择多列

sntx

注意:曾经有人问过类似的问题但它并不能完全回答我的问题。

如何根据满足某些布尔条件的大量列,对具有许多列的pandas数据框进行子集设置。

现在,我必须执行以下操作:

df[(df.column4 > a1) | (df.column23 < a2) | (df.column27 == a3) | ... 
    (df.column56 > a21) | (df.column72 < a22)]

谢谢

汤姆汤姆101

您必须以一种或另一种方式指定您的条件。您可以为每种情况创建单独的蒙版,最终将其减少为单个蒙版:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章