首页 > 解决方案 > 布尔索引的差异取决于索引符号

问题描述

我在熊猫中遇到了一些奇怪的事情,并试图找出原因。我基于应用于年龄列的简单 if/else 函数创建了一个新列:

import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/04_Apply/Students_Alcohol_Consumption/student-mat.csv')

def majority(x):
    if x >= 18:
        return True
    else:
        return False

df['legal_drinker'] = df.age.apply(majority)

但是现在,根据我的索引方式,我得到了两个不同的答案:

df[df['legal_drinker'] == True].shape
    >>(111, 13)

df[df.legal_drinker == True].shape`
    >>(1, 13)

有人知道为什么会这样吗?这完全让我困惑。

图片供参考:在此处输入图像描述

标签: pythonpandas

解决方案


推荐阅读