【问题标题】:How to compare 3 columns of DataFrame together, Python 3.6如何比较 3 列 DataFrame,Python 3.6
【发布时间】:2019-04-16 09:26:45
【问题描述】:

我有以下数据框,我想比较 3 列值并在另一列“Id_Name_Table_Matching”中更新 True/False

在我的代码下面:

L1_ID = ['Region', 'Col2', 'Col3', 'Col4', 'Col5']
L1_Name = ['Region', 'Col2', 'Col3', 'Col4', 'Col5']
L1_Table = ['Region', 'Col2', 'Col3', 'Col4', 'Col5']

DF1 = pd.DataFrame({'dimId': L1_ID, 'dimName': L1_Name, 'sqlTableColumn': L1_Table})

如果所有列的值都匹配,我想在“Id_Name_Table_Matching”中更新 true,否则为 false。 我需要如下脚本:

DF1['Id_Name_Table_Matching'] = DF1['dimId'] == DF1['dimName'] == DF1['sqlTableColumn']

【问题讨论】:

    标签: python python-3.x pandas list dataframe


    【解决方案1】:

    将第一列与第二列进行比较,然后将最后一列与 & 的链布尔掩码进行逐位比较 AND

    DF1['Id_Name_Table_Matching'] = (DF1['dimId'] == DF1['dimName']) & 
                                    (DF1['dimId'] == DF1['sqlTableColumn'])
    

    比较列表中定义的多个列的通用解决方案 - 所有过滤的列通过DataFrame.eq比较第一个,然后通过DataFrame.all检查每行的所有值是否为Trues:

    cols = ['dimId','dimName','sqlTableColumn']
    DF1['Id_Name_Table_Matching'] = DF1[cols].eq(DF1[cols[0]], axis=0).all(axis=1)
    print (DF1)
        dimId dimName sqlTableColumn  Id_Name_Table_Matching
    0  Region  Region         Region                    True
    1    Col2    Col2           Col2                    True
    2    Col3    Col3           Col3                    True
    3    Col4    Col4           Col4                    True
    4    Col5    Col5           Col5                    True
    

    详情

    print (DF1[cols].eq(DF1[cols[0]], axis=0))
       dimId  dimName  sqlTableColumn
    0   True     True            True
    1   True     True            True
    2   True     True            True
    3   True     True            True
    4   True     True            True
    

    【讨论】:

      【解决方案2】:

      看看这是否有帮助。使用.apply()

      df["Id_Name_Table_Matching"] = df.apply(lambda x: x.dimId == x.dimName == x.sqlTableColumn, axis = 1)
      print(df)
      

      输出:

          dimId dimName sqlTableColumn  Id_Name_Table_Matching
      0  Region  Region         Region                    True
      1    Col2    Col2           Col2                    True
      2    Col3    Col3           Col3                    True
      3    Col4    Col4           Col4                    True
      4    Col5    Col5           Col5                    True
      

      【讨论】:

      • 这是一个非常优雅的解决方案。谢谢。
      【解决方案3】:

      您也可以像这样使用Transpose 和.nunique()

      DF1.T.nunique().le(1)
      
      0    True
      1    True
      2    True
      3    True
      4    True
      dtype: bool
      

      【讨论】:

        猜你喜欢
        • 2020-02-01
        • 2019-04-09
        • 1970-01-01
        • 2015-03-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-11
        • 1970-01-01
        相关资源
        最近更新 更多