• 判断两个DataFrame和array的列(Series)是否相同


    问题:现在有两个DataFrame,第一个我们命名为 df1,第二个我们命名为 df2。两个 DataFrame 中各有一列数据,我需要横向判断这两列的数据是否相同(即:判断 df1 的第 1 行和 df2 的第 1 行是否相同,df1 第 2 行和 df2 第 2 行是否相同,依次类推),网上查看了一些解决办法,有的用循环遍历等都感觉不太正确,因为数据量太大也没办法验证。
    ————————————————

    import pandas as pd
    import numpy as np
    
    • 1
    • 2

    1、当数据长度相同时

    df1 = pd.DataFrame({'col1':['a','b']})
    df2 = pd.DataFrame({'col2':['a','c']})
    df = pd.concat([df1, df2], axis=1)
    df['result'] = np.where(df['col1']==df['col2'],'same','different')
    df
    
    • 1
    • 2
    • 3
    • 4
    • 5

    在这里插入图片描述
    2、当数据长度不同时

    df1 = pd.DataFrame({'col1':['a','b']})
    df2 = pd.DataFrame({'col2':['a','c','b']})
    df = pd.concat([df1, df2], axis=1)
    df['result'] = np.where(df['col1']==df['col2'],'same','different')
    df
    
    • 1
    • 2
    • 3
    • 4
    • 5

    在这里插入图片描述
    3、当都存在nan值的情况

    df1 = pd.DataFrame({'col1':['a','b',np.nan]})
    df2 = pd.DataFrame({'col2':['a','c',np.nan]})
    df = pd.concat([df1, df2], axis=1)
    df['result'] = np.where(df['col1']==df['col2'],'same','different')
    df
    
    • 1
    • 2
    • 3
    • 4
    • 5

    在这里插入图片描述

    1. 比较两个 array 中的某列,列名都为0,1,2
    np.where(np_subdf[:,2]==np_subdf_ori[:,2], 'same', 'different')
    Out[14]: array(['same', 'same', 'same', ..., 'same', 'same', 'same'], dtype=')
    
    • 1
    • 2
    a = np.where(np_subdf==np_subdf_ori, 'same', 'different')
    
    • 1

    在这里插入图片描述

    1. 判断某行(索引为2的行)
    a = np.where(np_subdf[2]==np_subdf_ori[2], 'same', 'different')
    
    • 1

    在这里插入图片描述

    参考资料:
    [1] https://blog.csdn.net/qq_40395868/article/details/116153969

  • 相关阅读:
    AOP——基本概念、底层原理
    java100-集合类简介
    windows安装wsl
    【Ant Design Pro】使用ant design pro做为你的开发模板(完结篇)上线部署项目
    vue开启splitChunks分包处理
    sample-encoder-video报错
    笔记-fabric.js的使用-参考官网
    Linux 环境搭建以及xshell远程连接
    【小沐学C++】git和github常见问题汇总
    BI财务分析 – 反映盈利水平利润占比的指标如何分析(上)
  • 原文地址:https://blog.csdn.net/weixin_46713695/article/details/126480138