如何根据部分标签过滤pandas数据框列

1 投票
1 回答
1359 浏览
提问于 2025-04-17 21:26

我想通过部分标签来过滤pandas数据框的列(类型是 pandas.core.index.Index)。

我在寻找一个内置的方法,能够实现和下面这段代码相同的效果:

partial_label = 'partial_lab'
columns = df.columns
columns = [c for c in columns if c.startswith(partial_label)]
df = df[columns]

有没有什么内置的方法可以做到这一点?

谢谢!

1 个回答

4

可能的解决方案:

df.filter(regex='partial_lab.*')

或者

idx = df.columns.to_series().str.startswith('partial_lab')
df.loc[:,idx]

撰写回答