我正在努力处理我的数据,我需要将数据组合起来使用,以便以后查找。
dataframe例子:
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
溶液:
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)