Python/Pandas-删除以字符串开头的列 [英] Python / Pandas - Drop columns that start with string

查看:1184
本文介绍了Python/Pandas-删除以字符串开头的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数据框

id    2013 Profits   2001 Revenues    1999 Assets...
31    xxxx           xxxx             xxxx
...

我想删除不以'201'开头的列(我只想保留2010年及以后的数据).

I want to drop the columns that do not start with '201' (I only want to keep the data 2010 and forward).

我该怎么办?

推荐答案

使用 pd.DataFrame.filter

df.filter(like='201')

   2013 Profits
id             
31         xxxx


正如@StevenLaan使用like所指出的,

将包括某些列,这些列的模式字符串在列名称的其他位置.我们可以通过使用regex来确保仅获取以模式字符串开头的列.


As pointed out by @StevenLaan using like will include some columns that have the pattern string somewhere else in the columns name. We can ensure that we only get columns that begin with the pattern string by using regex instead.

df.filter(regex='^201')

   2013 Profits
id             
31         xxxx

这篇关于Python/Pandas-删除以字符串开头的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆