[英]Appending unique mixed string using pandas or python
我有一個表或df(如果pandas有更好的方法),其中包含多個混合字符和字符串的列之一,我需要對它們進行計數並向其添加唯一的混合字符串,這是執行python循環的最佳方法或熊貓有一些語法可以做到嗎? 示例數據
col0 col1 col2
ENSG0001 E001 ENSG001:E001
ENSG0001 E002 ENSG001:E002
.
.
ENSG001 E028 ENSG001:E028
ENSG002 E001 ENSG002:E001
.
ENSG002 E012 ENSG002:E012
編輯:需要計算col0中的元素,而不是數字,我需要E001作為計數器並在col2中連接col0和col1
將由cumcount
+ astype
創建的Series
添加到string
+ zfill
。
df['col3'] = df['col0'] + ':E' +
df.groupby('col0').cumcount().add(1).astype(str).str.zfill(3)
print (df)
col0 col1 col2 col3
0 ENSG0001 E001 ENSG001:E001 ENSG0001:E001
1 ENSG0001 E002 ENSG001:E002 ENSG0001:E002
2 ENSG001 E028 ENSG001:E028 ENSG001:E001
3 ENSG002 E001 ENSG002:E001 ENSG002:E001
4 ENSG002 E012 ENSG002:E012 ENSG002:E002
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.