Pandas - 添加前导“0"到字符串值,所以所有值都等于 len [英] Pandas - Add leading "0" to string values so all values are equal len
问题描述
我有一列,code_x
.我将其转换为 .astype(str)
.一些示例值是 45362.0、75345.0、346157.0、572575.0
.我希望它们都是 6 位数字.又名:045362、075345、346157、572575
I have a column, code_x
. I converted it to .astype(str)
. Some example values are 45362.0, 75345.0, 346157.0, 572575.0
. I would like them all to be 6 digits. aka: 045362, 075345, 346157, 572575
我正在尝试以下操作,但它不起作用:f3[df3['code_x'].str.len() == 7] = "0" + df3[df3['code_x'].str.len() == 7]['code_x']代码>
I am trying the following, but it does not work:
f3[df3['code_x'].str.len() == 7] = "0" + df3[df3['code_x'].str.len() == 7]['code_x']
建议?
推荐答案
即使我和 @DSM 一起使用 zfill.但我认为使用lamba使它更清晰和易于阅读.
Even I am with @DSM for using zfill. But I think using lamba makes it much cleaner and easy to read.
In [1]: import pandas as pd
In [2]: df = pd.DataFrame([45362.0, 75345.0, 346157.0, 572575.0], columns=['code_x'])
In [3]: df.code_x.apply(lambda x: str(int(x)).zfill(6))
Out[3]:
0 045362
1 075345
2 346157
3 572575
Name: code_x, dtype: object
注意:在转换为字符串之前,我们将给定值转换为 int 以去除结果中的.0".
Note: We are converting a given value to int before converting to string to get rid of ".0" in results.
这篇关于Pandas - 添加前导“0"到字符串值,所以所有值都等于 len的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!