2012-10-05 124 views
23

我可以在DF任何列使用.map(func),如:熊猫数据框中:适用功能,所有列

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) 

是否有能够施加更Python的方式一个函数到所有列或整个框架(没有循环)?

+0

简化你的'lambda'到'拉姆达X:X> 1' – Blender

+0

@搅拌机 - 感谢,编辑... – root

+0

就指出了这一点。你并不需要编辑原始问题。 – Blender

回答

35

如果我理解你是对的,你正在寻找applymap方法。

>>> 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

0.20.0起,您可以使用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