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

如何利用pandas Series过滤DataFrame以保留指定列

解决方案

这事儿其实特别直观,因为你的Series s的索引刚好和DataFrame df的列名完全对应,直接用这个布尔Series作为列筛选器就行:

import pandas as pd

# 先还原你的数据
s = pd.Series(data=[True, False, True, True], index=['A', 'B', 'C', 'D'])
s.index.name = 'my_id'

df = pd.DataFrame({
    'A': [1, 2, 9, 4],
    'B': [9, 6, 7, 8],
    'C': [10, 91, 32, 13],
    'D': [43, 12, 7, 9]
})

# 核心代码:筛选列
filtered_df = df.loc[:, s]
print(filtered_df)

运行后你就能得到想要的结果:

A   C   D
0  1  10  43
1  2  91  12
2  9  32   7
3  4  13   9

简单解释一下:

  • df.loc[:, s]里的第一个冒号:表示保留所有行,第二个位置传入的s是布尔筛选器:pandas会自动匹配s的索引和df的列名,只保留s中值为True的列,自动移除值为False的列(也就是这里的B列)。
  • 要是你不想用loc,也可以直接写df[s],效果是一样的——因为当你把布尔Series传给DataFrame时,默认就是按列来筛选的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:31:46