팬더 데이터 프레임을 필터링하는 사용자 지정 함수를 만들고 싶습니다.
def df_filter(df, first_elem, col1, col2, other_elems):
'''
df: main dataframe
first_elem: first element to search
col1: first column to search for the first element
col2: second column to search for first element
other_elements: list with other elements to search for
'''
first_flt = df.loc[(df[col1] == first_elem) | (df[col2] == first_elem)]
second_flt = first_flt.loc[(first_flt[col1] == other_elems[0]) | (first_flt[col1] == other_elems[1])]
return second_flt
첫 번째 필터는 col1 및 col2에서 첫 번째 요소의 발생을 검색하고 이러한 행을 선택하여 first_flt를 생성하여 데이터 프레임을 필터링하는 것입니다.
두 번째 필터에서는 목록 (other_elems)에 제공된 더 많은 값을 검색하고 다시 필터링하고 싶습니다. 중요한 점은 내가 꽂 내용에 따라 다를 수 있습니다이 목록에있는 항목의 NR입니다. other_elems = ['one', 'two', 'three']
또는other_elems = ['one', 'two', 'three', four']
따라서이 부분은 other_elems의 요소 수에 따라 생성되어야합니다.
first_flt.loc[(first_flt[col1] == other_elems[0]) | (first_flt[col1] == other_elems[1])...]
이 작업을 수행하는 방법에 대한 아이디어가 있습니까?
경우 other_elems
반복 가능을, 당신은 DataFrame을 사용할 수 있습니다 ISIN 방법.
귀하의 예에서 :
second_flt = first_flt.loc[(first_flt[col1].isin(other_elems)]
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다