连接两列并用零填充以具有恒定长度

时间:2021-01-04 11:08:02

标签: python pandas

我有以下数据框:

 A       B
645     72436
645     73311
543     432666
432     6443
432     765321

我需要创建一个列 C,其长度为 10 位。 C 应通过将 B 连接到 A 并在两个连接列之间填充零来创建。
也就是说:

 A          B          C
645        72436      6450072436
645        73311      6450073311
543        432666     5430432666
432        6443       4320006443
432        765321     4320765321

AB 的串联将始终为 10 位或更少,因此不会出现 C 超过 10 位的情况。

3 个答案:

答案 0 :(得分:4)

首先,尝试在此处使用 A 提取 .str.len 中的位数,然后使用 np.power 和 base 作为 10

num_of_digits = df['A'].astype(str).str.len()
df['C'] = df['A'].mul(np.power(10, 10-num_of_digits)) + df['B']

     A       B           C
0  645   72436  6450072436
1  645   73311  6450073311
2  543  432666  5430432666
3  432    6443  4320006443
4  432  765321  4320765321

详情

num_of_digits = df['A'].astype(str).str.len() # This gives number of digits
# 0    3
# 1    3
# 2    3
# 3    3
# 4    3
# Name: A, dtype: int64

np.power(10, 10-num_of_digits) # If number has 3 digits then multiply it by 10-3
                               # i.e. 10^7
# Small example of `np.power`
# np.power(10, [2, 3, 4])
#  array([  100,  1000, 10000], dtype=int32)
#          10^2   10^3   10^4

df['A'].mul(np.power(10, 10-num_of_digits))
# 0    6450000000
# 1    6450000000
# 2    5430000000
# 3    4320000000
# 4    4320000000
# Name: A, dtype: int64

Now add df['B'] to it to get desired results

答案 1 :(得分:2)

按连接行的长度重复 0

df1 = df[['A','B']].astype(str)
s = df1.apply(lambda x: ''.join(['0'] * (10 - len(x.A + x.B))), axis=1)

df['new'] = df1.A + s + df1.B
print (df)
     A       B         new
0  645   72436  6450072436
1  645   73311  6450073311
2  543  432666  5430432666
3  432    6443  4320006443
4  432  765321  4320765321

编辑:为了提高处理整数的性能,使用 np.log10 转换为整数并添加 1 表示位数,然后乘以 10 的乘方 A

a = np.log10(df['A']).astype(int).add(1)

df['new'] = df.A * 10 ** (10 - a) + df.B
print (df)
     A       B         new
0  645   72436  6450072436
1  645   73311  6450073311
2  543  432666  5430432666
3  432    6443  4320006443
4  432  765321  4320765321

答案 2 :(得分:1)

你可以这样做:

A = df['A'].astype('str')
B = df['B'].astype('str')

missing = 10 - (A.str.len() + B.str.len())

df['C'] = A + pd.Series(['0' * e for e in missing]) + B
print(df)

输出

     A       B           C
0  645   72436  6450072436
1  645   73311  6450073311
2  543  432666  5430432666
3  432    6443  4320006443
4  432  765321  4320765321

只使用数学,你可以做到,(非常类似于@jezrael):

import numpy as np
missing = 10 - (np.log10(df['A']).astype(int) + 1)
tens = 10 ** missing

df['C'] = (df['A'] * tens) + df['B']
print(df)

输出

     A       B           C
0  645   72436  6450072436
1  645   73311  6450073311
2  543  432666  5430432666
3  432    6443  4320006443
4  432  765321  4320765321

但要注意涉及 log10 的解决方案,请参阅 this

相关问题