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

如何从糖尿病样本数据集提取指定2列的10条样本数据?

提取DataFrame指定两列的10条样本数据

你用df.get("gender", "heart_disease")只拿到gender列的原因是:get()方法只能接收单个列名作为第一个参数,第二个参数是当该列不存在时返回的默认值,并不是用来指定第二列的。

要提取gender和heart_disease两列并获取前10条样本,直接用方括号传入列名列表即可,再配合head(10)获取前10行:

最简写法

print(df[["gender", "heart_disease"]].head(10))

分步写法(更清晰)

# 先筛选出需要的两列
target_cols = df[["gender", "heart_disease"]]
# 取前10条数据
top_10_samples = target_cols.head(10)
# 输出结果
print(top_10_samples)

可选:避免列不存在的报错

如果担心指定的列可能不在数据集中,可以先做个校验:

wanted_cols = ["gender", "heart_disease"]
# 过滤出数据集中实际存在的列
valid_cols = [col for col in wanted_cols if col in df.columns]

if valid_cols:
    print(df[valid_cols].head(10))
else:
    print("指定的列在数据集中不存在")

内容的提问来源于stack exchange,提问作者Girish bhagwanani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 15:53:09