我的資料框是:

當 Hospital 列中具有相同值的行在 GeneralRepresentation 列中具有不同的值時,我想使用 Pandas 重命名 Hospital。當 Hospital 列中具有相同值的行在 GeneralRepresentation 列中具有相同值時,則不會對 Hospital 進行重命名。
我想要的效果如下圖:

uj5u.com熱心網友回復:
只需要改變邏輯,你需要groupby cumcount的unique價值
g = df.groupby('Hospital')['GeneralRepresentation']
s1 = g.transform(lambda x :x.factorize()[0] 1).astype(str)
s2 = g.transform('nunique')
df['Hospital'] = np.where(s2==1, df['Hospital'], df['Hospital'] '_' s1,)
df
Hospital GeneralRepresentation
0 a a
1 b_1 b
2 b_2 c
3 c_1 d
4 c_2 e
5 d f
6 d f
uj5u.com熱心網友回復:
利用重復創建布林值。將布林值傳遞到np.where(condition, if condition true, if condition is false). cumcount 將有助于生成增量連續,當它變成字串時可以連接到原始名稱
df['Hospital']=np.where(((df['Hospital'].duplicated(keep=False))&(df['GeneralRepresentation'].duplicated(keep=False))),df['Hospital'] '_' (df.groupby('Hospital').cumcount() 1).astype(str),df['Hospital'])
uj5u.com熱心網友回復:
您可以使用:
dup = ~df.duplicated(keep=False)
g_count = df.groupby("Hospital").cumcount() 1
count = df.groupby("Hospital")['GeneralRepresentation'].transform('count')
df['Hospital'] = np.where((dup) & (count>1), df['Hospital'] '_' g_count.astype(str), df['Hospital'])
OUTPUT
Hospital GeneralRepresentation
0 UMC a
1 MGH_1 b
2 MGH_2 j
3 NMH_1 o
4 NMH_2 a
5 MSH d
6 MSH d
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/399128.html
