pandas DataFrame:应用功能到所有列 [英] Pandas DataFrame: apply function to all columns
本文介绍了 pandas DataFrame:应用功能到所有列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以在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)
pre>
是否有更多的pythonic方式将函数应用于所有列或整个框架(无循环)?
解决方案如果我明白你是正确的,你正在寻找
applymap
方法。>>>打印df
ABC
0 -1 0 0
1 -4 3 -1
2 -1 0 2
3 0 3 2
4 1 - 1 0
>>>>打印df.applymap(lambda x:x> 1)
ABC
0 False False
1 False True False
2 False False True
3 False True True
4 False False False
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)?
解决方案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
这篇关于 pandas DataFrame:应用功能到所有列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文