Home > Backend Development > Python Tutorial > 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

王林
Release: 2023-05-19 15:49:06
forward
2513 people have browsed it

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
Copy after login

AB
011
122
233
347
4hellohello
5worldword

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
Copy after login
##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
Copy after login
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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template