提问者:小点点

DataFrame:将函数应用于所有列


我可以使用。映射(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)

我还可以:

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

有没有一种更蟒蛇的方法可以将函数应用于所有列或整个框架(没有循环)?


共2个答案

匿名用户

如果我没弄错的话,您正在寻找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.20。0以后,您可以使用变换

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

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