60

I can use .map(func) on any column in a df, like:

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)

I could also:

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

Is there a more pythonic way to apply a function to all columns or the entire frame (without a loop)?

0

3 Answers 3

102

If I understand you right, you're looking for the applymap method.

>>> 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
Sign up to request clarification or add additional context in comments.

Comments

18

From 0.20.0 onwards, you can use 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

And, for this simplistic case, why not just use 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

Comments

3

From version 2.1.0 of pandas, use map instead of applymap

applymap has been deprecated.

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

Prefer using the comparison operators directly over using map:

In [102]: df > 1
Out[102]: 
           A      B      C
    0  False  False  False
    1  False   True  False
    2  False  False   True
    3  False   True   True
    4  False  False  False

Also, you could use apply or transform.

If you don't need additional parameters, they will seem to be basically the same, except for using the comparison operator which is the recommended choice in OP's case.

Read the documentation for more details

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.