You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在pandas DataFrame中按名称查找数据并处理不存在的情况?

根据姓名查找DataFrame中的年龄和体重信息

原始代码

import pandas as pd
import numpy as np

names = pd.Series(['Bill','Bob','Joe','Sam'])
age = pd.Series([16,15,17,15])
weight = pd.Series([145,164,155,148])
df = pd.concat([names,age,weight],axis=1)
df.columns=['Name','Age','Weight']
[name,age,weight]=df.iloc[2]
# Now [name, age, weight] = ['Joe', 17, 155]

需求

  1. 未知'Joe'的索引时,获取他的Age和Weight
  2. 查找'Tim'的信息时,明确提示该姓名不存在于DataFrame中

解决方案

方法1:布尔索引筛选

直接通过姓名匹配筛选行,提取目标列并判断结果是否为空:

# 查找Joe的信息
joe_info = df[df['Name'] == 'Joe'][['Age', 'Weight']]
if not joe_info.empty:
    print(joe_info.values[0])  # 输出 [17 155]
else:
    print("姓名不存在")

# 查找Tim的信息
tim_info = df[df['Name'] == 'Tim'][['Age', 'Weight']]
if not tim_info.empty:
    print(tim_info.values[0])
else:
    print("姓名不存在")

方法2:将Name设为索引后用loc访问

把Name列设为索引,用loc直接定位,通过try-except捕获不存在的情况:

# 设置Name为索引
df_indexed = df.set_index('Name')

# 查找Joe
try:
    joe_data = df_indexed.loc['Joe', ['Age', 'Weight']]
    print(joe_data.values)  # 输出 [17 155]
except KeyError:
    print("姓名不存在")

# 查找Tim
try:
    tim_data = df_indexed.loc['Tim', ['Age', 'Weight']]
    print(tim_data.values)
except KeyError:
    print("姓名不存在")

方法3:使用query方法筛选

用query语句筛选目标行,通过长度判断是否存在匹配结果:

# 查找Joe
joe_result = df.query("Name == 'Joe'")[['Age', 'Weight']]
if len(joe_result) > 0:
    print(joe_result.iloc[0].values)
else:
    print("姓名不存在")

# 查找Tim
tim_result = df.query("Name == 'Tim'")[['Age', 'Weight']]
if len(tim_result) > 0:
    print(tim_result.iloc[0].values)
else:
    print("姓名不存在")

内容的提问来源于stack exchange,提问作者Ted Ersek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 20:17:12