在Pandas中按名称识别多个列

2024-04-24 08:25:12 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种方法可以使用文本匹配或正则表达式来选择列的子集?在

在R中是这样的:

attach(iris) #Load the 'Stairway to Heaven' of R's built-in data sets
iris[grep(names(iris),pattern="Length")] #Prints only columns containing the word "Length"

Tags: oftheto方法in文本irisdata
2条回答

您可以为此使用^{}方法(使用axis=1过滤列名)。此功能有不同的可能性:

  • 相当于if 'Length' in col

    df.filter(like='Length', axis=1)
    
  • 使用regex(但是,它使用的是re.search,而不是{},因此您可能需要调整regex):

    df.filter(regex=r'\.Length$', axis=1)
    

使用Python的in语句,其工作方式如下:

#Assuming iris is already loaded as a df called 'iris' and has a proper header
iris = iris[[col for col in iris.columns if 'Length' in col]]
print iris.head()

或者,使用正则表达式

^{pr2}$

第一个会跑得更快,但第二个会更准确。在

相关问题 更多 >