Pandas DataFrame ApplyMap方法

时间:2014-02-12 11:11:22

标签: python pandas

我想尝试Pandas applymap对象DataFrame方法的功能。以下是用例:

假设我的DataFrame df1如下:

Age   ID       Name
0   27  101    John
1   22  102    Bob
2   19  103    Alok
3   27  104    Tom
4   32  105    Matt
5   19  106    Steve
6    5  107    Tom
7   55  108    Dick
8   67  109    Harry

现在我想创建一个标志变量,其逻辑是如果元素的长度小于2,则flag = 1 else flag = 0。

为了以元素方式运行,我想使用applymap方法。因此,我创建了一个用户定义的函数,如下所示:

def f(x): 
   if len(str(x))>2: 
       df1['Flag']=1
   else: 
      df1['Flag']=0

然后我跑了df1.applymap(f)给了:

    Age    ID  Name
0  None  None  None
1  None  None  None
2  None  None  None
3  None  None  None
4  None  None  None
5  None  None  None
6  None  None  None
7  None  None  None
8  None  None  None

而不是使用标志值创建标志变量。如何使用applymap

实现所需的功能

我们不能在用户定义的函数中使用DataFrame变量名或pandas语句吗?即,df1['Flag']的定义中f()有效吗?

1 个答案:

答案 0 :(得分:9)

函数f(x)对于pandas并不特殊 - 它只是一个常规的python函数。因此f范围内的唯一数据是变量x df1的其他成员不可用。

来自applymap docs:

  

func:function

     

Python函数,从单个值返回单个值

所以你可以试试这个:

def f(x):
    if len(str(x)) <= 3: return 1
    else: return 0

应用时,为帧中的每个元素输出1/0:

df1.applymap(f)

>>>
   Age  ID  Name
0    1   1     0
1    1   1     1
2    1   1     0
3    1   1     1
4    1   1     0
5    1   1     0
6    1   1     1
7    1   1     0
8    1   1     0

要使用结果在每行中添加另一个变量,每行需要一个值,例如

df1['Flag'] = df1.applymap(f).all(axis=1).astype(bool)

>>> df1

   Age   ID   Name   Flag
0   27  101   John  False
1   22  102    Bob   True
2   19  103   Alok  False
3   27  104    Tom   True
4   32  105   Matt  False
5   19  106  Steve  False
6    5  107    Tom   True
7   55  108   Dick  False
8   67  109  Harry  False

另请查看https://stackoverflow.com/a/19798528/1643946,其中包含applymap以及applymap