看过来
《pandas 教程》 持续更新中,提供建议、纠错、催更等加作者微信: gr99123(备注:pandas教程)和关注公众号「盖若」ID: gairuo。跟作者学习,请进入 Python学习课程。欢迎关注作者出版的书籍:《深入浅出Pandas》 和 《Python之光》。
DataFrame.select() 是 pandas 3.1.0 新增的方法,用于从 DataFrame 中选择指定的列子集,并返回一个新的 DataFrame。
DataFrame.select() 的主要功能:
pandas.col() 表达式来计算新列DataFrame.select(*args, **kwargs)
参数说明如下:
| 参数 | 类型 | 说明 |
|---|---|---|
*args |
hashable / Expression / 这些类型的列表 | 要选择的列标签,或对 DataFrame 求值的表达式。如果传入单个列表(如 Index 或数组),其元素即为要选择的项;列表不能与其他位置参数混用。重复请求同一个标签会返回该列多次。对于 MultiIndex,非元组标签选择整个第一级,元组标签选择多级。 |
**kwargs |
callable / Expression / Series / scalar / array-like / dict | 额外的计算列,每个关键字参数名即为新列名,值按照 DataFrame.assign() 的规则解析:callable 和表达式会在 DataFrame 上求值,其他值按原样赋值(遵循 DataFrame.__setitem__() 的对齐和广播规则)。 |
返回值:
DataFrame重要规则:
MultiIndex 时,计算列必须使用完整的元组名称,此时只允许位置参数。需要使用 .rename(...) 来重命名表达式。import pandas as pd
df = pd.DataFrame({
"first_name": ["John", "Alice", "Bob"],
"last_name": ["Smith", "Cooper", "Marley"],
"age": [61, 22, 35],
})
print("原始数据:")
print(df)
输出:
first_name last_name age
0 John Smith 61
1 Alice Cooper 22
2 Bob Marley 35
result = df.select("first_name", "age")
print(result)
输出:
first_name age
0 John 61
1 Alice 22
2 Bob 35
result = df.select(["last_name", "age"])
print(result)
输出:
last_name age
0 Smith 61
1 Cooper 22
2 Marley 35
result = df.select("last_name", "first_name", "age")
print(result)
输出:
last_name first_name age
0 Smith John 61
1 Cooper Alice 22
2 Marley Bob 35
result = df.select("age")
print(type(result)) # <class 'pandas.core.frame.DataFrame'>
print(result)
输出:
age
0 61
1 22
2 35
注意:即使只选了一列,返回的也是 DataFrame 而非 Series。这与
df["age"]返回 Series 不同。
pd.col() 表达式 + 关键字参数创建计算列result = df.select(
"first_name",
pd.col("age"), # 位置参数:保留原列
age_months=pd.col("age") * 12 # 关键字参数:创建新列
)
print(result)
输出:
first_name age age_months
0 John 61 732
1 Alice 22 264
2 Bob 35 420
关键区别:
- 位置参数中的
pd.col("age"):结果保留底层列名age- 关键字参数
age_months=pd.col("age") * 12:关键字名age_months成为新列名
result = df.select(
"first_name",
age_months=pd.col("age") * 12,
age_days=pd.col("age_months") * 30, # 引用前面计算出的 age_months
)
print(result)
输出:
first_name age_months age_days
0 John 732 21960
1 Alice 264 7920
2 Bob 420 12600
这是
select相比简单列选择的最大优势:可以在一次调用中完成多步计算,且后一步可以引用前一步的结果。
df_multi = pd.DataFrame(
,
columns=pd.MultiIndex.from_tuples([
("names", "first_name"),
("names", "last_name"),
("other", "age"),
]),
)
print("MultiIndex 原始数据:")
print(df_multi)
输出:
names other
first_name last_name age
0 John Smith 61
1 Alice Cooper 22
2 Bob Marley 35
按第一级标签选择:
result = df_multi.select("names")
print(result)
输出:
first_name last_name
0 John Smith
1 Alice Cooper
2 Bob Marley
使用元组选择多级:
result = df_multi.select(("names", "last_name"), ("other", "age"))
print(result)
输出:
names other
last_name age
0 Smith 61
1 Cooper 22
2 Marley 35
| 方法 | 用途 | 返回值 |
|---|---|---|
df.select("a", "b") |
按列名/表达式选择列,支持计算列 | DataFrame |
df[["a", "b"]] |
按列名选择列(基础索引) | DataFrame |
df["a"] |
选择单列 | Series |
df.filter(items=["a", "b"]) |
按标签筛选行或列 | DataFrame |
df.select_dtypes(include=["int"]) |
按数据类型选择列 | DataFrame |
df.assign(new_col=...) |
添加新列(返回新 DataFrame) | DataFrame |
select的独特之处在于:它既能选列,又能计算新列,还能保证执行顺序,是一站式列操作工具。
select 再 assign 的两步操作。pd.col() 表达式,写出更声明式的列操作代码。.loc 更直观。select 是安全的选择。select 返回的是新 DataFrame,不会修改原数据。KeyError。简而言之,它是 pandas 3.1 引入的一个列选择 + 列计算一体化方法,配合 pd.col() 表达式使用效果最佳,能让代码更简洁、更声明式。
更新时间:2026-11-01 17:14:22 标签:pandas python select 选择