使用def函数映射数据帧

时间:2017-06-30 17:03:24

标签: python-3.x pandas anaconda

错误: AttributeError: 'DataFrame' object has no attribute 'map'

代码: 我创建了一个函数来根据不同列中的值对我的数据帧中的一些时间事件(行)进行分类。

def usage(x):
    if x['Dest']==x['Origin']: return 'round'
    elif x['Origin']==x['next_dest']:
        if x['Dest']==x['next_origin']: return 'perfectsym'
        else: return 'nonperfectsym'
    else: 'None'

有了这个,我希望能够使用map函数对新列中的条目进行分类,如下所示:

All_data['usagetype'] = All_Data.map(usage)

但这不起作用。

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

<强>解决方案:

数据框级别的map相当于apply

All_data['usagetype'] = All_Data.apply(usage, axis=1)

替代和评论:

但是对于类似这样的事情,一个相当简单的逐行条件,你可以使用np.where获得更快的计算:

def  usage2(df):
    return np.where(df['Dest'] == df['Origin'], 'round',
                    np.where(df['Origin'] == df['next_dest'],
                             np.where(df['Dest'] == df['next_origin'],
                                      'perfectsym', 'nonperfectsym'),
                             None))

All_data['usagetype'] = usage2(All_Data)

在1000行上快一百倍:

df = pd.DataFrame(np.random.randint(0, 4, size=(1000, 4)),
                  columns=['Dest', 'Origin', 'next_dest', 'next_origin'])

%timeit usage2(df)
1000 loops, best of 3: 463 µs per loop

%timeit df.apply(usage, axis=1)
10 loops, best of 3: 46.1 ms per loop

我还建议删除None周围的引号,就像我在上面的usage2中所做的那样,除非您明确要求字符串“None”而不是NaN值。