텍스트 일치 또는 정규 표현식을 사용하여 열의 하위 집합을 선택하는 방법이 있습니까? 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"
텍스트 일치 또는 정규 표현식을 사용하여 열의 하위 집합을 선택하는 방법이 있습니까? 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"
filter
방법을 사용할 수 있습니다 (열 이름을 필터링하려면 axis=1
을 사용하십시오).
df.filter(like='Length', axis=1)
정규식 사용 (단,이 re.search
하지 re.match
을 사용됩니다, 그래서 당신은 정규식을 조정할 가능성이있다) :
상당 if 'Length' in col
에 :이 기능은 다른 가능성을 가지고
df.filter(regex=r'\.Length$', axis=1)
파이썬의 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()
또는
import re
iris = iris[[col for col in iris.columns if re.match(r'\.Length$',col)]]
print iris.head()
첫 번째는 더 빠르게 실행되지만 두 번째는 더 정확합니다.
아주 좋은 정보 @joris. 그러나 컬럼 이름과 함께 다른 문자를 포함하는 컬럼 이름을 가져와야합니다. 예를 들어 "Length_1", "Length_2", "Width_1", "Width_2"등이 내 열 이름입니다. 내 필터 함수는 df.filter (like = col + '_', axis = 1)와 같습니다. 여기서 col은 "Length", "Width"등과 같은 값을 가지며 값을 가져 오지 않습니다. 어떤 생각을 수정해야합니까? – JKC
정규 표현식으로 할 수 있어야합니다. 예를 들어'regex = r "Length | Width"' – joris