Python连接两列但保持固定长度

我有一个如下所示的 DataFrame。我想连接前两列。


如果它们的连接长度是<13那么我想在它们之间添加 0,以便长度变为 13。

如果它们的连接长度是>=13那么我只想连接。

d = {'col1': [123456, 2, 1234567], 'col2': [1234567, 4, 1234567]}

df = pd.DataFrame(data=d)

df

df['var3'] = df.col1.astype(str) + df.col1.astype(str)

df

在第二行的情况下,我希望2和2之间为11 0,而不是'22'。我希望将第三行保持原样,因为串联的长度为>13。


MMMHUHU
浏览 159回答 2
2回答

素胚勾勒不出你

您可能希望别人做任何事情之前的数字转换成字符串,所以我认为col1和col2都是字符串。首先,找到组合的字符串长度以及缺少多少个零:pads = 13 - (df.col1.str.len() + df.col2.str.len())然后生成必要的填充并连接列和填充:df['var3'] = df.col1 + pads.apply(lambda x: x * '0') + df.col2#0&nbsp; &nbsp; &nbsp;1234561234567#1&nbsp; &nbsp; &nbsp;2000000000004#2&nbsp; &nbsp; 12345671234567

胡子哥哥

对于每一行,创建一个包含 3 个值的元组:字符串1字符串2两个字符串的长度与13(或任何目标长度)之间的差x = pd.Series(list(zip(df['col1'].astype(str),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;df['col2'].astype(str),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;13 - (df['col1'].astype(str) + df['col2'].astype(str)).str.len())))然后,使用字符串方法ljust将左字符串填充为0,并将其添加到右字符串。将所有内容分配给新列。df['var3'] = x.apply(lambda x: x[0].ljust(x[2], '0') + x[1])
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python