python - 获取满足条件的行的最大值
问题描述
我有一个看起来像这样的 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']
有没有更快的方法来做到这一点?
解决方案
您的第一种方法是可靠的,但这是一个简单的选择:
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
推荐阅读
- webrtc - 由于混淆主机地址,当对等点不在 NAT 后面时,WebRTC 在现代浏览器中不起作用
- karate - 如何在空手道中评估 Json Key 中变量的值?
- c# - 需要身份验证时不调用 GetAuthCredentials
- android - 为什么我的 kivy 应用程序在加载后立即关闭?
- python - 自定义愿景:剩余配额
- python - 在Django的views.py中从html选择中获取值
- ios - 在 swiftUI 上使用 ondelete 擦除多个字符串
- java - 修复:我已将 sinch jar 文件添加到 libs 文件夹并作为 android studio 中的库,但是当我导入 sinch 或相关类时,它不显示导入选项
- google-apps-script - Google App Script MailApp 停止发送电子邮件
- flutter - 如何使用 2 个流,其中流 2 取决于流 1?