使用 pandas 或 python 附加独特的混合字符串
Appending unique mixed string using pandas or python
我有一个 table 或 df(如果 pandas 有更好的方法)其中一列有多个混合字符和字符串,我需要计算它们并附加一个唯一的混合字符串对此,执行 python 循环或 pandas 有一些语法的最佳方法是什么?示例数据
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
to string
+ zfill
创建的列 Series
。
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
我有一个 table 或 df(如果 pandas 有更好的方法)其中一列有多个混合字符和字符串,我需要计算它们并附加一个唯一的混合字符串对此,执行 python 循环或 pandas 有一些语法的最佳方法是什么?示例数据
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
to string
+ zfill
创建的列 Series
。
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