![](/img/trans.png)
[英]How to update dataframe columns to a specific list and if those columns are not present, they can be either null or NA or 0s
[英]Is there ways to add 0s in a specific columns of dataframe to match specific number of digits?
我有两个表,其中一列包含特定 ID。
例如,
表A
cust_id
1234
32145
1235692
9293159
表B
cust_id
0001234
0032145
1235692
9293159
我正在尝试使用 sql 应用内连接,但由于它们不完全匹配,因此使用内连接子句的结果中缺少前两个 ID 1234 (0001234)、32145 (0032145)。
所以这是我的问题。
比如1234只有4位,但是转换后变成了7位,前面加了三个0 --> 0001234。
如果可能的话,对于这种特定情况,我希望我可以使用 Python 或 SQL 获得帮助。
提前致谢。
对于python,这可以使用pandas 轻松处理。
假设 cust_id 已经是一个字符串列:
>>> df.cust_id.apply(lambda x: x.zfill(7))
0 0001234
1 0032145
2 1235692
3 9293159
对于 SQL,您声明您使用的是 SSMS,因此这意味着 SQL Server。 不幸的是,SQL Server 没有开箱即用的 LPAD 功能,但您可以使用以下方法复制它:
REPLACE(STR(<column_name>, <desired_length>),' ','0')
例如:
with cust_ids as (
select * from (
values
('1234'),
('32145'),
('1235692'),
('9293159')
) a (cust_id)
)
select
cust_id,
REPLACE(STR(cust_id, 7),' ','0') as padded_cust_id
from cust_ids
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.