python - 如何在Python中将列中字符串的格式更改为3位数字 "000"

标签 python string pandas format

我有两列:一列称为“样式”,另一列称为“颜色”。我想创建一个名为“Product_Code”的列,连接样式然后颜色。 “颜色”列应包含三位数字,但该列包含 float ,并且某些行包含两位数字,因为不存在前导“0”。这是我想要的示例:

   Product_Code   Style   Color   Price
0       323-010     323      10      10
1       400-111     400     111       8
2       323-023     323      23       5

最佳答案

您可以使用zfill来填充左侧零和字符串连接:

df['Product_Code'] = df.Style.astype(str) + '-' + df.Color.astype(str).str.zfill(3)

关于python - 如何在Python中将列中字符串的格式更改为3位数字 "000",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61893542/

相关文章:

python - 从正态分布中进行拉丁超立方采样 (Python)

python - 如何在 kivy-python 中使用带多线程的时钟对象更新进度条?

java - 如果使用 new 运算符创建对象,为什么要在 String 中使用 intern 方法?

string - 如果字符串包含 case 语句

python - 计算 lambda 函数中上述出现的次数

Python - Pandas 导出到 csv 或 dat 文件删除无或 numpy.nan

python - 将系列分配给具有不相等索引的 DataFrame

python - 如何在 Visual Studio 2017 中将包添加到 python

python - 将按 df 分组转换为带有字典列表的字典

c# - 在 C# 中计算校验和