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 | B | Is the data in column AB equal? |
0 | 1 | 1 | 1 |
1 | 2 | 2 | 1 |
2 | 3 | 3 | 1 |
3 | 4 | 7 | 0 |
4 | hello | hello | 1 |
5 | world | word | 0 |
Method 2: Direct judgment
# 方法二:直接判断
df_data['AB列数据是否相等2'] = (df_data['A'] == df_data['B'])*1
df_data
| A | B | Is the data in column AB equal? | Is the data in column AB equal?2 |
0 | 1 | 1 | 1 | 1 |
1 | 2 | 2 | 1 | 1 |
2 | 3 | 3 | 1 | 1 |
3 | 4 | 7 | 0 | 0 |
##4
hello |
hello |
1 |
1 |
|
5
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!