2016-08-17 1 views
1

다음 함수를 실행 중이지만 어떻게 든 길이 조건 (if 부분)을 고려해야하는 데 어려움을 겪고 있습니다.람다 (lambda)가 적용된 파이썬 팬더는 어려움을 적용합니다.

stringDataFrame.apply(lambda x: x.str.replace(r'[^0-9]', '') if (len(x) >= 7) else x)

어떻게 든 단지 내가 잘못 여기에 내가 갇혀있다 뭐하는 거지 어떤 이유로 x.str.replace(r'[^0-9]', '') 부분을 실행 : 함수 경우에만 그것은 단순히 첫 번째 부분을 실행합니다. 별도로 각각의 값에 대한 작업을 필요로 할 때 당신은 applymap 사용할 수 있습니다

+0

당신이 당신의 문제를 보여주는 예제를 제공 할 수 있습니까? – IanS

+1

x는 계열이고 len (x)는 해당 계열의 길이입니다. 개별 문자열의 길이를 확인 하시겠습니까? – ayhan

답변

1

때문에 all column (Series)와 apply 작동합니다. 그런 다음

대신 str.replace를 사용, 정규식 등에서 특정 요소를 뽑아 오기 위해 더 좋은 작품 re.sub을 사용

print (stringDataFrame.applymap(lambda x: re.sub(r'[^0-9]', '', x) if (len(x) >= 7) else x)) 

샘플 :

import pandas as pd 
import re 

stringDataFrame = pd.DataFrame({'A':['gdgdg454dgd','147ooo2', '123ss45678'], 
           'B':['gdgdg454dgd','x142', '12345678a'], 
           'C':['gdgdg454dgd','xx142', '12567dd8']}) 

print (stringDataFrame) 
      A   B   C 
0 gdgdg454dgd gdgdg454dgd gdgdg454dgd 
1  147ooo2   x142  xx142 
2 123ss45678 12345678a  12567dd8 

print (stringDataFrame.applymap(lambda x: re.sub(r'[^0-9]', '', x) if (len(x) >= 7) else x)) 
      A   B  C 
0  454  454  454 
1  1472  x142 xx142 
2 12345678 12345678 125678 
+0

@jezrael에 감사드립니다. applymap을 시도했지만 문제가 'str.replace'를 사용하는 것처럼 보입니다. – Jeff

+0

이 질문에 해당하는 간단한 내용입니다. 나는 그것이 람다와 함수에 관해서는 끔찍하다. 하지만 추가로'x.contains ("tel | cel | cell", case = False)를 추가하여 두 가지 조건을 원합니다. 그러면식이 다음과 같이 보일 것입니다. stringInfoFrame.applymap (len (x)> = 7) & lt; stringDataFrame.applymap (lambda x : re.sub (r '[^ 0-9]', '' (x.contains ("tel | cel | cell", case = False))) else x)'@jezrael – Jeff

+0

평범한 파이썬이 필요합니다.'print (stringDataFrame.applymap (lambda x : re.sub (r '[[^ [ 'cel', 'tel', 'cell']에있는 ext의 경우 any (x iner (x)가 7 인 경우) else x))' – jezrael