我正在努力处理数据,我需要合并数据以供以后使用。
示例数据框:
rtu rail module
0 213 3 29
1 217 2 28
2 223 2 26
3 224 3 26
4 229 4 29
5 225 3 27
6 222 3 28
7 226 3 29
我想在格式rtu:rail(module)
示例中合并这3列:
213:003(029)
谢谢。
将值转换为字符串并加入Series.str.zfill
:
df['new'] = (df['rtu'].astype(str) + ':' +
df['rail'].astype(str).str.zfill(3) + '(' +
df['module'].astype(str).str.zfill(3) + ')')
print (df)
rtu rail module new
0 213 3 29 213:003(029)
1 217 2 28 217:002(028)
2 223 2 26 223:002(026)
3 224 3 26 224:003(026)
4 229 4 29 229:004(029)
5 225 3 27 225:003(027)
6 222 3 28 222:003(028)
7 226 3 29 226:003(029)
f-string
s的解决方案:
df['new'] = df.apply(lambda x: f"{x['rtu']}:{str(x['rail']).zfill(3)}({str(x['module']).zfill(3)})", axis=1)
并且没有f-string
s:
df['new'] = df.apply(lambda x: str(x['rtu']) + ':' + str(x['rail']).zfill(3) + '(' + str(x['module']).zfill(3) + ')', axis=1)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句