我有以下数据框,我想比较 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']
最佳答案
将第一列与第二列进行比较,然后通过 &
与最后一个列和链式 bool 值掩码进行按位 AND
比较:
DF1['Id_Name_Table_Matching'] = (DF1['dimId'] == DF1['dimName']) &
(DF1['dimId'] == DF1['sqlTableColumn'])
比较列表中定义的多个列的通用解决方案 - 所有过滤列均按第一个列进行比较 DataFrame.eq
然后通过DataFrame.all
检查每行的所有值是否为True
:
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
关于python - 如何比较 DataFrame 的 3 列,Python 3.6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53282823/