所以我有一個資料集看起來像:
| 可樂 | B欄 | 科爾C |
|---|---|---|
| 啦?啦?啦 | 納米 | 退休 |
| 波波波 | 采購訂單 | 退休 |
| 切切 | 中興 | 作業 |
| 拉拉拉 | AB | 作業 |
JSON看起來像:
{
"NM":"Nano Master",
"PO":"Prank Operation"
}
我想更新When COL A When
Col C = Retired AND COL B = JSON 內的資料
如果在查詢中,它可能看起來像:
UPDATE TABLE SET COL_A = JSON WHERE COL_C='RETIRED' AND COL_B = JSON->>'key'
我想使用 pandas lambda 函式來實作這一點。我試著用
df[COL_A] = df.apply(lambda x: "col_b" if x["COL_B"] == "RETIRED" else x["COL_A"], axis=1)
uj5u.com熱心網友回復:
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
或者
# 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
uj5u.com熱心網友回復:
這是另一種方式:
df['Col A'] = df['Col A'].mask(df['Col C'].eq('RETIRED') & df['Col B'].isin(dict1.keys())).fillna(df['Col B'].map(dict1))
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
資料
dict1 = {
"NM":"Nano Master",
"PO":"Prank Operation"
}
uj5u.com熱心網友回復:
嘗試這個:
#load json from local,
with open('json_example.json') as json_data:
dictt= json.load(json_data)
#or
#dictt={"NM":"Nano Master","PO":"Prank Operation"}
df['Col A']=np.where(df['Col C']=='RETIRED',df['Col B'].replace(dictt),df['Col A'])
print(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
'''
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/519759.html
標籤:Python熊猫
上一篇:檢查另一個熊貓資料框中的條件
