2012-10-05 1 views
23

모든 컬럼에 함수를 적용 :팬더 DataFrame : 나는이처럼 DF의 모든 열을 <code>.map(func)</code>을 사용할 수 있습니다

df=DataFrame({'a':[1,2,3,4,5,6],'b':[2,3,4,5,6,7]}) 

df['a']=df['a'].map(lambda x: x > 1) 

또한 수 :

df['a'],df['b']=df['a'].map(lambda x: x > 1),df['b'].map(lambda x: x > 1) 

이 적용보다 파이썬 방법이 모든 열 또는 전체 프레임에 대한 함수 (루프없이)?

+0

람다'로'lambda'는 X 단순화 : X> 1' – Blender

+0

@ 블렌더 - 감사합니다, 편집 ... – root

+0

그냥 그 지적. 원래 질문을 편집 할 필요가 없습니다. – Blender

답변

35

나는 당신을 이해한다면 applymap 방법을 찾고 있습니다.

이후 0.20.0에서
>>> print df 
    A B C 
0 -1 0 0 
1 -4 3 -1 
2 -1 0 2 
3 0 3 2 
4 1 -1 0 
>>> print df.applymap(lambda x: x>1) 
     A  B  C 
0 False False False 
1 False True False 
2 False False True 
3 False True True 
4 False False False 
+0

@ BrenBarn - 네, 이것이 제가 찾고 있던 것입니다. 문서에서 그것을 알아 채지 못했습니다. 감사. – root

1

,이 단순한 경우에, transform

In [578]: df.transform(lambda x: x > 1) 
Out[578]: 
     A  B  C 
0 False False False 
1 False True False 
2 False False True 
3 False True True 
4 False False False 

In [579]: df 
Out[579]: 
    A B C 
0 -1 0 0 
1 -4 3 -1 
2 -1 0 2 
3 0 3 2 
4 1 -1 0 

을 사용하고 있습니다, 왜 그냥 df > 1를 사용할 수 있습니까?

In [582]: df > 1 
Out[582]: 
     A  B  C 
0 False False False 
1 False True False 
2 False False True 
3 False True True 
4 False False False 
관련 문제