본문 바로가기
파이썬

파이썬 Selecting columns with condition on Pandas DataFrame

by º기록 2020. 11. 3.
반응형

이와 같은 데이터 프레임이 있습니다.

    col1    col2
0   something1  something1
1   something2  something3
2   something1  something1
3   something2  something3
4   something1  something2  

col1 또는 col2 에서 something1 이있는 모든 행을 필터링하려고합니다. 열에 조건 논리가 필요한 경우 df [df.col1 == 'something1'] 을 사용하여 수행 할 수 있지만 여러 열로 수행 할 수있는 방법이 있습니까?

 

해결 방법

 


print ((df == 'something1').all(1))
0     True
1    False
2     True
3    False
4    False
dtype: bool

print (df[(df == 'something1').all(1)])
         col1        col2
0  something1  something1
2  something1  something1

편집하다:


print (df)
         col1        col2 col3
0  something1  something1    a
1  something2  something3    s
2  something1  something1    r
3  something2  something3    a
4  something1  something2    a

cols = df.columns[df.columns.isin(['col1','col2'])]
print (cols)
Index(['col1', 'col2'], dtype='object')

print (df[(df[cols] == 'something1').all(1)])
         col1        col2 col3
0  something1  something1    a
2  something1  something1    r

 

참조 페이지 https://stackoverflow.com/questions/37663931

 

 

반응형

댓글