Home  >  Article  >  Backend Development  >  How to determine whether two columns of data are equal in DataFrame in Python

How to determine whether two columns of data are equal in DataFrame in Python

王林
王林forward
2023-05-19 15:49:062451browse

Data preparation

import numpy as np
import pandas as pd
import json
import psycopg2

data = {
    'A':[1,2,3,4,'hello','world'],
    'B':[1,2,3,7,'hello','word']
}
df_data = pd.DataFrame(data = data)
df_data

A B
0 1 1
1 2 2
2 3 3
3 4 7
4 hello hello
5 world word

Method 1: Write function judgment

# 方法一:写函数判断
# 判断是否相等
def is_equal_or_not(a,b):
    if a == b:
        return 1
    else:
        return 0
# 数据处理
df_data['AB列数据是否相等'] = df_data.apply(lambda x : is_equal_or_not(x['A'],x['B']),axis = 1)
df_data
##A BIs the data in column AB equal?01111221233134704hellohello15 worldword0

Method 2: Direct judgment

# 方法二:直接判断
df_data['AB列数据是否相等2'] = (df_data['A'] == df_data['B'])*1
df_data

ABIs the data in column AB equal?Is the data in column AB equal?20111112 2112331134700##45

hello hello 1 1
world word 0 0

The above is the detailed content of How to determine whether two columns of data are equal in DataFrame in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete