'Match dataframe rows one by one and return corresponding row values [duplicate]
I have two data frames dfA, dfB. dfA has two columns value and action, and dfB has one column action. I want to match the B with A on 'Value' column and return the 'Action' item, if not it will return the string "NOT MATCHED".
dfA:
value action
"user" "enter"
"password" "enter"
"login" "click"
"customerid" "enter"
"phonenumber" "enter"
"submit" "click"
dfB:
value
"submit"
"password"
"sign in"
"cutomerid"
"phonenumber"
"user"
I want my output dataframe to look like this:
dfB:
value action
"submit" click
"password" enter
"sign in" notmatched
"cutomerid" enter
"phonenumber" enter
"user" enter
Solution 1:[1]
Using pandas merge functionality and left join desired output can be achieved. While using merge() first two arguments are the dataframes that we want to merge, 3rd argument is to merge on which column so there "value" is specified, as 4th argument "left" is passed which denotes that both the dataframe should be merged using left join.
Left join: Left join operation provides all the rows from 1st dataframe and matching rows from the 2nd dataframe. If the rows are not matched in the 2nd dataframe then they will be replaced by NaN.
At last NaN values are replaced with string "notmatched" as to achieve desired result.
import pandas as pd
value = ["user","password","login","customerid","phonenumber","submit"]
action = ["enter","enter","click","enter","enter","click"]
df1 = pd.DataFrame(list(zip(value,action)))
df1.columns = ["value","action"]
# print(df1)
value = ["submit","password","sign in","cutomerid","phonenumber","user"]
df2 = pd.DataFrame(value)
df2.columns = ["value"]
# print(df2)
df3 = pd.merge(df2,df1,on="value",how="left")
df3["action"] = df3["action"].fillna("notmatched")
print(df3)
Edit : As OP has asked question in a comment, below can be used to print :
for index, row in df3.iterrows():
if (row["action"]=="notmatched"):
print("not match")
else:
print(row["action"])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
