连接具有特定宽度整数的列

问题描述 投票:3回答:3

我有一个带有两个整数列的数据框'df':

C1 C2
8  49
.. ..

从这里,我想创建一个新列,用于连接具有特定宽度的两列。 C1应为两位数宽,C2应为三位数宽,以便生成的列如下所示:

CODESUM 
08049

前0对我来说不太重要。

到目前为止,我已尝试使用str()函数与str(df.C1),但没有成功。还有其他想法吗?

python string pandas dataframe
3个回答
6
投票

使用双str.zfill

df['new'] = df.C1.astype(str).str.zfill(2) + df.astype(str).C2.str.zfill(3)

1
投票

你可以简单地尝试以下方法:

df['CODESUM'] = df['C1'].astype(str).str.zfill(1) + df['C2'].astype(str).str.zfill(2)

“+”适用于str连接


0
投票

使用列表理解和格式化字符串(Python 3.6+):

df['new'] = [f'{i:02d}{j:03d}' for i, j in df[['C1', 'C2']].values]

print(df)

   C1  C2    new
0   8  49  08049

F字符串通常可以提高性能:

df = pd.concat([df]*100000)

%timeit [f'{i:02d}{j:03d}' for i, j in df[['C1', 'C2']].values]               # 458ms / loop
%timeit [str(i).zfill(2)+str(j).zfill(3) for i, j in df[['C1', 'C2']].values] # 1.03s / loop
%timeit df.C1.astype(str).str.zfill(2) + df.astype(str).C2.str.zfill(3)       # 1.02s / loop
© www.soinside.com 2019 - 2024. All rights reserved.