Python/Pandas - 删除以字符串开头的列

abu*_*nte 3 python pandas

我有这样的数据帧

id    2013 Profits   2001 Revenues    1999 Assets...
31    xxxx           xxxx             xxxx
...
Run Code Online (Sandbox Code Playgroud)

我想删除不以'201'开头的列(我只想保留数据2010和转发).

我怎样才能做到这一点?

piR*_*red 7

使用 pd.DataFrame.filter

df.filter(like='201')

   2013 Profits
id             
31         xxxx
Run Code Online (Sandbox Code Playgroud)

正如@StevenLaan指出的那样,like将包含一些列,这些列在列名中的其他位置具有模式字符串.我们可以确保只使用regex替换来获取以模式字符串开头的列.

df.filter(regex='^201')

   2013 Profits
id             
31         xxxx
Run Code Online (Sandbox Code Playgroud)


Ste*_*aan 5

这将确保仅保留以201开头的列.

df[[c for c in df.columns if c.startswith('201')]]
Run Code Online (Sandbox Code Playgroud)

同样可以实现

df.filter(regex='^201')
Run Code Online (Sandbox Code Playgroud)