Sitemap
Mr Farkhod Khushaktov

Mr Farkhod Khushaktov

I am Data Scientist from Uzbekistan Please follow me

Data Matching Analysis in Python

6 min readAug 23, 2023

--

Farkhod Khushvaktov | 2023 23 August

Data Matching is the task of finding records that refer to the same entity. Normally, these records come from multiple data sets and have no common entity identifiers, but data matching techniques can also be used to detect duplicate records within a single database.

Identifying and matching records across multiple data sets is a very challenging task for many reasons. First of all, the records usually have no attribute that makes it straightforward to identify the ones that refer to the same entity, so it is necessary to analyze attributes that provide partial identification, such as names and dates of birth (for people) or title and brands (for products). Because of that, data matching algorithms are very sensitive to data quality, which makes it necessary to pre-process the data being linked in order to ensure a minimal quality standard, at least for the key identifier attributes.

Another fact that introduces additional complexity to this problem is that data can change over time. For example, if two databases of people information are being matched against each other, it is not rare to find cases where the same person has different addresses (since people occasionally move) or even different names (since people can get married or divorced).

Data matching problems generally have no training data available (a data set with matches that we know are valid across the analyzed databases) and so it is not easy to approach the problem with a supervised learning algorithm, as it would be possible in many machine learning applications.

The databases that are subject of data matching analysis can be very large. In the worst case, each record of one database has to be compared to all other records on the other one. Tasks like this can be extremely computationally expensive and hard to be accomplished in feasible time, since this approach involves an algorithm with quadratic complexity. To deal with this situation and make the data matching scalable, some kind of indexing technique can be applied to reduce the number of record pairs that will be compared, but it is not always easy to design an index that removes most non-matches and, at the same time, does not affect the quality of the matching pairs.

Example

  • E-Commerce: this area has grown dramatically in the past few years and it is common for many comparison shopping platforms to have to link products from multiple online stores that have different descriptions. For example, Store A can have the product Notebook — X35 8GB RAM 13" LED and Store B can refer the same notebook as 13" X35 Notebook 8GB RAM 500GB HD.

Let’s Start Coding

First We Should Download Causal Inference Library

!pip install Causalinference

And we should Call some Libraries to use into Matching

#Libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import scipy.stats as st
from causalinference import CausalModel

OK you can see there are some new Library which are Scipy stats and Causal inference

Load Dataset from Directory

df = pd.read_csv('school.csv')
df = df.iloc[:, 1 : ]
df.head()

We drop some unnecessary columns

Press enter or click to view image in full size

Let’s T Test with loop

we going to T_test by catholic column we will split 0 and 1 / yes or no version in loop of each column

columns = ['number_places_lived','mom_age', 'dad_age', 'mom_score', 'dad_score']
stat = {}
p_value = {}

for i in columns:
group1 = df.where(df["catholic"] == 0).dropna()[i]
group2 = df.where(df['catholic'] == 1).dropna()[i]
stat[i], p_value[i] = st.ttest_ind(group1, group2)
p_ttest = pd.DataFrame.from_dict(data = p_value, orient="Index")
p_ttest.columns = ["P_values"]
p_ttest
Our Result

if P_value greater than 0.5 it is similar else on similar

Let’s Chi Square Analysis

in this section we are going to do chi square therefore we use crosstab function to make categorical data I recommend crosstab function to use how does it work for yourself

categorical = ['poverty', 'food_stamps']
p = {}

for i in categorical:
tap = pd.crosstab(index=df[i],
columns=df["catholic"])
stat, p[i], dof, exf = st.chi2_contingency(tap)
Chisquare = pd.DataFrame.from_dict(p, 'Index')
Chisquare.columns = ['p_value']
Chisquare

Let’s Data Preparation Section

First we have some text column like Race, mom_education and dad_education we should transform to Binary data therefore we will do

df.race.value_counts()

Transform all text column in one code space because there are many code

df['race_white'] =  np.where(df.race == 'WHITE, NON-HISPANIC', 1, 0)
df['race_hispanic'] = np.where((df.race == 'HISPANIC, RACE NOT SPECIFIED') |
(df.race == 'HISPANIC, RACE NOT SPECIFIED'), 1, 0)
df['race_black'] = np.where(df.race == 'BLACK OR AFRICAN AMERICAN, NON-HISPANIC', 1, 0)
df['race_asian'] = np.where(df.race == 'ASIAN', 1, 0)

# Mom_education and Dad_education transform
df['dad_higher_education'] = np.where((df.dad_education == "BACHELOR'S DEGREE") |
(df.dad_education == "MASTER'S DEGREE (MA, MS)") |
(df.dad_education == "DOCTORATE OR PROFESSIONAL DEGREE "), 1, 0)
df['mom_higher_education'] = np.where((df.mom_education == "BACHELOR'S DEGREE") |
(df.mom_education == "MASTER'S DEGREE (MA, MS)") |
(df.mom_education == "DOCTORATE OR PROFESSIONAL DEGREE "), 1, 0)

# data cleaning from text column after transform
df = df.drop(columns = ['race','dad_education', 'mom_education'])

Isolate treat y confounder data

We should isolate data to make model

#Isolate Confounder, Treat, y
treat = df.catholic.values
y = df.score_standardized.values
confounder = df.drop(columns = ['catholic', 'score_standardized']).values

Common Support Region

We can use logistic regression to understand better and visualize

import statsmodels.api as st
confounder_csr = st.add_constant(confounder)
csr_model = st.Logit(treat, confounder_csr).fit()
print(csr_model.summary())

Now We compare to Visualize our model probability result

#model Predict 
probabilities = csr_model.predict(confounder_csr)
#add actual value and predicted value into one list each other
df_prop = np.vstack([treat, probabilities]) # vstack add 2 list to 1 list
df_prop = np.transpose(df_prop) # this transpose function add each if there are 2 list into one list example i[0][0] + i[1][0]
# split treated values and non_treated values
non_treat = df_prop[:, 0] == 0 # get only 0 index have been 0 value
non_treat = df_prop[non_treat, 1] #this function get 1 index from the list of each index
treated = df_prop[:, 0] == 1
treated = df_prop[treated, 1]


it is ready to visualize with logistic regression

sns.kdeplot(non_treat, shade= True, color = 'Red')
sns.kdeplot(treated, shade= True, color = 'green');

this our predicted value’s plot version

Let’s Matching Model

model = CausalModel(y, treat, confounder)
model.est_via_matching(bias_adj = True)
print(model.estimates)
Press enter or click to view image in full size

we need ate values

model.estimates['matching']['ate']

OUTPUT>> -0.156209947464663

Get Mr Farkhod Khushaktov’s stories in your inbox

Join Medium for free to get updates from this writer.

conclusion We can Robustness

ate = {}
i = 1
while i < 100:
#Sampling
sample = df.sample(1000)
#Isolate y, treat, confounder
treat = sample.catholic.values
y = sample.score_standardized.values
confounder = sample.drop(columns = ['catholic', 'score_standardized']).values
#Matching Model
model = CausalModel(y, treat, confounder)
model.est_via_matching(bias_adj = True)
#Store Ate
ate[i] = model.estimates['matching']['ate']

#Increase number of Loop
i += 1

and we can plot its values to understand what happen how relationship eath other

ate = pd.Series(ate)
print(ate.hist())
print(ate.mean())

OOOHH Yeah we have done it

have good day Bye

Assalamu Alaykum

--

--

Mr Farkhod Khushaktov
Mr Farkhod Khushaktov

I am Data Scientist from Uzbekistan Please follow me