根據:

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

當我在
但是我想要的是醫院沒有GeneralRepresentation的時候,醫院的名字保持不變,效果就像第二張圖,我該如何修改這段代碼來滿足我的要求?
uj5u.com熱心網友回復:
問題在于缺失值,因為缺失值被factorize設定為-1,所以如果為最后 2 行添加1get 0,在我的解決方案中NaN之前被替換為空字串groupby以防止它:
g = df.fillna({'GeneralRepresentation':''}).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)
print (df)
Hospital GeneralRepresentation
0 a a
1 b_1 b
2 b_2 c
3 c_1 d
4 c_2 e
5 d NaN
6 t NaN
uj5u.com熱心網友回復:
利用 np.select(listof conditions, list of choices, alternative)
a=~(df['GeneralRepresentation'].str.contains('\w'))
b= ((df['GeneralRepresentation'].str.contains('\w'))&(df['Hospital'].duplicated(keep=False))&(df['GeneralRepresentation'].duplicated(keep=False)))
df['Hospital'] np.select([a,b],[df['Hospital'] '_' (df.groupby('Hospital').cumcount() 1).astype(str),''],df['Hospital'])
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/398836.html
