我有这样的数据帧
id 2013 Profits 2001 Revenues 1999 Assets...
31 xxxx xxxx xxxx
...
Run Code Online (Sandbox Code Playgroud)
我想删除不以'201'开头的列(我只想保留数据2010和转发).
我怎样才能做到这一点?
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)
这将确保仅保留以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)