Pandas DataFrame筛选包含字符串的列的3种方法

Pandas是Python中强大的数据分析库,如果你想高效处理数据,熟练掌握DataFrame的用法是必不可少的。本文介绍3种筛选DataFrame中包含特定字符串的列的方法。


我们以一个简单的DataFrame为例:

   col1  col2  col3  col4  col5
0     1     4     7    10    13   
1     2     5     8    11   14
2     3     6     9    12   15

1. 选择包含"col"的列

使用`filter`和`like`参数:

df.filter(like='col')

这会返回包含"col"字符串的全部列:

   col1  col2  col3  col4  col5
0     1     4     7    10   13    
1     2     5     8    11   14  
2     3     6     9    12   15


2. 选择末尾为特定字符串的列 

继续使用`filter`和`like`参数:

df.filter(like='4') 

这会返回末尾包含"4"的列:

   col4  
0    10      
1    11
2    12


3. 选择以特定字符串开头的列

同样使用`filter`和`like`参数,但增加`axis=1`指定我们操作的是列:

df.filter(like='c', axis=1) 


这会返回以"c"开头的列:

   col1  col2  col3  col4  col5
0     1     4     7    10   13     
1     2     5     8    11   14
2     3     6     9    12   15  


总之,通过`filter`和`like`参数以及`axis`参数的构造,Pandas提供了简洁高效的方法来筛选DataFrame中包含特定字符串的列。

你可能感兴趣的:(python,python,pandas,数据分析)