Pandas如何选择包含特定字符串的列

594 阅读2分钟

你可以使用以下方法来选择pandas DataFrame中包含一个特定字符串的列。

方法1:选择包含一个特定字符串的列

df.filter(regex='string1')

方法2:选择包含几个字符串中的一个字符串的列

df.filter(regex='string1|string2|string3') 

下面的例子展示了如何在实践中使用这些方法中的每一个,即以下的pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'mavs': [10, 12, 14, 15, 19, 22, 27],
                   'cavs': [18, 22, 19, 14, 14, 11, 20],
                   'hornets': [5, 7, 7, 9, 12, 9, 14],
                   'spurs': [10, 12, 14, 13, 13, 19, 22],
                   'nets': [10, 14, 25, 22, 25, 17, 12]})

#view DataFrame
print(df)

   mavs  cavs  hornets  spurs  nets
0    10    18        5     10    10
1    12    22        7     12    14
2    14    19        7     14    25
3    15    14        9     13    22
4    19    14       12     13    25
5    22    11        9     19    17
6    27    20       14     22    12

例1:选择包含一个特定字符串的列

下面的代码显示了如何使用filter()函数,只选择名称中包含 "avs "字符串的列:

#select columns that contain 'avs' in the name
df2 = df.filter(regex='avs')

#view DataFrame
print(df2)

   mavs  cavs
0    10    18
1    12    22
2    14    19
3    15    14
4    19    14
5    22    11
6    27    20

只有名称中包含 "avs "的列被返回。

在这个例子中,"mavs "和 "cavs "是唯一被返回的列。

例2:选择包含几个字符串之一的列

下面的代码显示了如何使用**filter()**函数,只选择名称中包含 "avs "或 "ets "的列:

#select columns that contain 'avs' in the name
df2 = df.filter(regex='avs|ets')

#view DataFrame
print(df2)

   mavs  cavs  hornets  nets
0    10    18        5    10
1    12    22        7    14
2    14    19        7    25
3    15    14        9    22
4    19    14       12    25
5    22    11        9    17
6    27    20       14    12

只有名称中包含 "avs "或 "ets "的列被返回。

请注意,竖条(|)是pandas中的 "OR"运算符。

你可以随意将这些 "OR "运算符串联起来,以选择包含多个不同字符串之一的列。

其他资源

下面的教程解释了如何在pandas中执行其他常见任务:

Pandas:如何将列移动到数据框架的前面
Pandas:如何检查列是否包含字符串
Pandas:如何向数据框架添加空列(3个例子