2017-04-20 75 views
1

我有一個表或df(如果pandas有更好的方法)與多個混合字符和字符串的列之一,我需要統計它們並追加一個唯一的混合字符串,做一個python循環或熊貓的最佳方式是什麼?例如數據使用熊貓或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作爲計數器的元素和串聯COL0和COL1在COL2

+0

您可以添加所需的輸出嗎? – jezrael

+0

這看起來就像'df ['col2'] = df ['col0'] +':'+ df ['col1']' – EdChum

+0

請參閱編輯 – sbradbio

回答

2

加入由cumcount + astype創建的列Seriesstring + 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 
+0

太棒了!非常感謝您的及時回覆@jezrael – sbradbio

+1

很高興能幫助你,美好的一天! – jezrael