Python Pandas DataFrame:将函数应用于所有列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12741092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas DataFrame: apply function to all columns
提问by root
I can use .map(func)on any column in a df, like:
我可以.map(func)在 df 中的任何列上使用,例如:
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)?
是否有更 Pythonic 的方式将函数应用于所有列或整个框架(没有循环)?
采纳答案by BrenBarn
If I understand you right, you're looking for the applymapmethod.
如果我理解正确,那么您正在寻找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
回答by Zero
From 0.20.0onwards, you can use transform
从那时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
And, for this simplistic case, why not just use df > 1?
而且,对于这种简单的情况,为什么不直接使用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

