python - 零填充熊猫列
问题描述
我有以下数据框,其中 col_1 是整数类型:
print(df)
col_1
100
200
00153
00164
如果位数等于 3,我想添加两个零:
final_col
00100
00200
00153
00164
我试过:
df.col_1 = df.col_1.astype(int).astype(str)
df["final_col"] = np.where(len(df["col_1"]) == 3, "00" + df.col_1, df.col_1 )
但它不会产生预期的输出(当条件满足时它不会添加两位数)。
我该如何解决?
解决方案
另一种使用方式series.str.pad()
:
df.col_1.astype(str).str.pad(5,fillchar='0')
0 00100
1 00200
2 00153
3 00164
您的解决方案应更新为:
(np.where(df["col_1"].astype(str).str.len()==3,
"00" + df["col_1"].astype(str),df["col_1"].astype(str)))
但是当字符串的长度小于 5 且不等于 3 时,这将不起作用,因此我建议您不要使用它。
推荐阅读
- python - 如何逐个补丁写入 png/tiff 文件?
- javascript - React JS 导入错误 - 未找到模块:您尝试导入项目 src/ 目录之外的 ../actions
- listview - 如何在主详细信息页面中设置列表视图的默认选定项
- mysql - SQL 查询以提取最近的部分以及比该日期早 30 天的任何内容。
- typescript - 为什么构造函数属性不解析为 Typescript 中的类的类型?
- android - 当有人点击我的共享意图时如何检查是否安装了应用程序
- prolog - 如何使用 Swi-prolog 运行 aleph 程序?
- python - python应用程序崩溃的Heroku部署?
- python - 从网页导入原始数据作为数据框
- javascript - 为什么过渡组不起作用?