열 중 하나의 하위 문자열을 기반으로 파이썬 데이터 프레임을 필터링하려고합니다.Python, Pandas : 함수를 기반으로하는 데이터 프레임의 행을 필터링하십시오.
ID 필드의 위치14 번이 < = 9 인 경우 행을 유지하고 싶습니다. 9보다 크면 행을 삭제하고 싶습니다.
예 :
ABCD-3Z-A93Z-01A-11R-A37O-07 -> 계속
ABCD-3Z-A93Z-11A-11R-A37O-07 -> 드롭
나는 아래의 해결책에 도달 할 수 있었지만 더 빠르고 효율적인 방법이 있어야한다고 생각합니다.
import pandas as pd
# Enter some data. We want to filter out all rows where the number at pos 13,14 > 9
df = {'ID': ['ABCD-3Z-A93Z-01A-11R-A37O-07', 'ABCD-6D-AA2E-11A-11R-A37O-07', 'ABCD-6D-AA2E-01A-11R-A37O-07',
'ABCD-A3-3307-01A-01R-0864-07', 'ABCD-6D-AA2E-01A-11R-A37O-07', 'ABCD-6D-AA2E-10A-11R-A37O-07',
'ABCD-6D-AA2E-09A-11R-A37O-07'],
'year': [2012, 2012, 2013, 2014, 2014, 2017, 2015]
}
# convert to df
df = pd.DataFrame(df)
# define a function that checks if position 13&15 are > 9.
def filter(x):
# that, if x is a string,
if type(x) is str:
if int(float(x[13:15])) <= 9:
return True
else:
return False
else:
return False
# apply function
df['KeepRow'] = df['ID'].apply(filter)
print(df)
# Now filter out rows where "KeepRow" = False
df = df.loc[df['KeepRow'] == True]
print(df)
# drop the column "KeepRow" as we don't need it anymore
df = df.drop('KeepRow', axis=1)
print(df)
위치에 의해 값이 다음
boolean indexing
에 의해
float
및 필터로 변환하기위한
브릴리언트, 감사합니다! 훨씬 쉬워! Stackoverflow는 5 분 안에 대답 만 수락 할 수 있다고 말합니다. 그럴거야. – Laura