【问题标题】:Pandas DataFrame Apply EfficiencyPandas DataFrame 应用效率
【发布时间】:2017-05-30 13:30:24
【问题描述】:

我有一个数据框,如果另一个数据框中有匹配的值,我不想在其中添加具有某种状态的列。我有当前有效的代码:

df1['NewColumn'] = df1['ComparisonColumn'].apply(lambda x: 'Match' if any(df2.ComparisonColumn == x) else ('' if x is None else 'Missing'))

我知道这条线很丑,但我觉得它效率低下。你能提出一个更好的方法来进行这种比较吗?

【问题讨论】:

    标签: python-3.x pandas apply


    【解决方案1】:

    您可以使用np.whereisinisnull

    创建一些虚拟数据:

    np.random.seed(123)
    df = pd.DataFrame({'ComparisonColumn':np.random.randint(10,20,20)})
    df.iloc[4] = np.nan #Create missing data
    df2 = pd.DataFrame({'ComparisonColumn':np.random.randint(15,30,20)})
    

    匹配np.where:

    df['NewColumn']  = np.where(df.ComparisonColumn.isin(df2.ComparisonColumn),'Matched',np.where(df.ComparisonColumn.isnull(),'Missing',''))
    

    输出:

        ComparisonColumn NewColumn
    0               12.0          
    1               12.0          
    2               16.0   Matched
    3               11.0          
    4                NaN   Missing
    5               19.0   Matched
    6               16.0   Matched
    7               11.0          
    8               10.0          
    9               11.0          
    10              19.0   Matched
    11              10.0          
    12              10.0          
    13              19.0   Matched
    14              13.0          
    15              14.0          
    16              10.0          
    17              10.0          
    18              14.0          
    19              11.0          
    

    【讨论】:

    • 非常感谢 - 我已经实现了它,它更快一点,而且它肯定更清晰。你能评论一下为什么它更快吗?我的原始帖子中可能缺少的东西是比较是文本比较。使用 numpy 执行文本比较似乎很有趣。
    • @user3535074 是的,apply 操作通常有点慢,我只是使用 Numpy 进行 if then 控制,并且使用 Pandas 和 isin 函数进行比较。
    猜你喜欢
    • 2019-11-14
    • 1970-01-01
    • 1970-01-01
    • 2014-12-16
    • 1970-01-01
    • 1970-01-01
    • 2016-09-26
    • 2018-07-26
    • 2018-11-23
    相关资源
    最近更新 更多