[英]Appending unique mixed string using pandas or python
I have a table or df(if pandas has a better way) with one of the columns with multiple mixed character and string, i need to count them and append a unique mixed string to it, what would be best way to do a python loop or pandas has some syntax to do it? 我有一个表或df(如果pandas有更好的方法),其中包含多个混合字符和字符串的列之一,我需要对它们进行计数并向其添加唯一的混合字符串,这是执行python循环的最佳方法或熊猫有一些语法可以做到吗? example data
示例数据
col0 col1 col2
ENSG0001 E001 ENSG001:E001
ENSG0001 E002 ENSG001:E002
.
.
ENSG001 E028 ENSG001:E028
ENSG002 E001 ENSG002:E001
.
ENSG002 E012 ENSG002:E012
Edit: Need to count the elements in col0 and instead of a number I need E001 as the counter and concatenate col0 and col1 in col2 编辑:需要计算col0中的元素,而不是数字,我需要E001作为计数器并在col2中连接col0和col1
Add to column Series
created by cumcount
+ astype
to string
+ zfill
. 将由
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.