Pandas DataFrame:将函数应用于所有列

57
我可以在一个数据框的任何列上使用`.map(func)`,例如:

我可以在一个数据框的任何列上使用.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)

有没有更Pythonic的方法可以将一个函数应用于所有列或整个数据框(而不使用循环)?


将您的 lambda 简化为 lambda x: x > 1 - Blender
1
只是指出一下而已。你不需要编辑原始问题。 - Blender
2个回答

98

如果我理解得对,您正在寻找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

1
@ BrenBarn -- 是的,这正是我在寻找的东西。我没有从文档中注意到它。谢谢。 - root

18

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接