Issue
So i have a dataset looks like:
Col A | Col B | Col C |
---|---|---|
Nanana | NM | RETIRED |
Popopo | PO | RETIRED |
Cecece | ZX | WORK |
Lalala | AB | WORK |
And a JSON Looks Like:
{
"NM":"Nano Master",
"PO":"Prank Operation"
}
I wanted to update When COL A When
Col C = Retired AND COL B = Data inside JSON
If in query it might looks like:
UPDATE TABLE SET COL_A = JSON WHERE COL_C='RETIRED' AND COL_B = JSON->>'key'
I wanted to achieve this using a pandas lambda function. i tried to use
df[COL_A] = df.apply(lambda x: "col_b" if x["COL_B"] == "RETIRED" else x["COL_A"], axis=1)
Solution
d={"NM":"Nano Master","PO":"Prank Operation"}
# Using np.where, check for the compound condition
# when true, return mapped value from dictionary
# else leave value as is
df['Col A']=np.where (df['Col C'].eq('RETIRED') & df['Col B'].map(d).notna(),
df['Col B'].map(d),
df['Col A'])
df
OR
# check for condition in mask, when true return a mapping from dict
# else leave the value as is
df['Col A']=df['Col A'].mask(df['Col C'].eq('RETIRED') & df['Col B'].map(d).notna(), df['Col B'].map(d))
df
Col A Col B Col C
0 Nano Master NM RETIRED
1 Prank Operation PO RETIRED
2 Cecece ZX WORK
3 Lalala AB WORK
Answered By - Naveed
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.