首页 > 解决方案 > 获取满足条件的行的最大值

问题描述

我有一个看起来像这样的 DataFrame:

| Age | Married | OwnsHouse |
| 23  | True    | False     |
| 35  | True    | True      |
| 14  | False   | False     |
| 27  | True    | True      |

我想找到已婚并拥有房屋的人的最高年龄。这里的答案是 35。我的第一个想法是:

df_subset = df[df['Married'] == True and df['OwnsHouse'] == True]
max_age = df_subset.max()

但是,数据集很大(50MB),我担心这会在计算上很昂贵,因为它会通过数据集两次。

我的第二个想法是:

max_age = 0
for index, row in df.iterrows():
    if(row[index]['Married] and row['index']['OwnsHouse'] and row[index]['Age] > max_age):
    max_age = row[index]['Age']

有没有更快的方法来做到这一点?

标签: pythonpython-3.xpandas

解决方案


您的第一种方法是可靠的,但这是一个简单的选择:

df[df['Married'] & df['OwnsHouse']].max()

Age          35.0
Married       1.0
OwnsHouse     1.0
dtype: float64

或者,只是年龄:

df.loc[df['Married'] & df['OwnsHouse'], 'Age'].max()
# 35

如果您有多个布尔列,我会建议一些更具可扩展性的东西,

df[df[['Married', 'OwnsHouse']].all(axis=1)].max()

Age          35.0
Married       1.0
OwnsHouse     1.0
dtype: float64

在哪里,

df[['Married', 'OwnsHouse']].all(axis=1)

0    False
1     True
2    False
3     True
dtype: bool

这与,

df['Married'] & df['OwnsHouse']

0    False
1     True
2    False
3     True
dtype: bool

但不是手动查找 N 个布尔掩码的 AND,.all而是为您完成。

query是另一种选择:

df.query("Married and OwnsHouse")['Age'].max()
# 35

它不需要计算掩码的中间步骤。


您的方法足够快,但是如果您想进行微优化,这里有一些 numpy 的更多选项:

# <= 0.23
df[(df['Married'].values & df['OwnsHouse'].values)].max()
df[df[['Married', 'OwnsHouse']].values.all(axis=1)].max()
# 0.24+
df[(df['Married'].to_numpy() & df['OwnsHouse'].to_numpy())].max()
df[df[['Married', 'OwnsHouse']].to_numpy().all(axis=1)].max()

Age          35.0
Married       1.0
OwnsHouse     1.0
dtype: float64

尽管您可能只想要年龄。做这个

df.loc[(df['Married'].to_numpy() & df['OwnsHouse'].to_numpy()), 'Age'].max()
# 35

如果您喜欢更多 numpy,请执行以下操作:

df.loc[(
   df['Married'].to_numpy() & df['OwnsHouse'].to_numpy()), 'Age'
].to_numpy().max()
# 35

或者更好的是,扔掉熊猫,

df['Age'].to_numpy()[df['Married'].to_numpy() & df['OwnsHouse'].to_numpy()].max()
# 35

推荐阅读