python - 合并数据框的列并用零填充空数字
问题描述
我有一个带有两列的熊猫数据框,第一个标题为“字母”有两个字母(例如 AB),另一个标题为“数字”有数字(从 1 到 9999)。现在我想合并它们,使“Letters”= XY 和“Numbers”= 4 的第一行变为 XY0004,基本上确保两个单元格被合并,但数字单元格添加了额外的 0 零。带有 ZW 和 333 的第 2 行将变为 ZW0333。带有 AB 和 1234 的第 3 行将变为 AB1234。我怎样才能做到这一点?
解决方案
使用 pandasastype
转换int
并str
使用zfill
添加前导零:
# Example dataframe
df = pd.DataFrame({'Letters':['AB', 'XY', 'ZW'],
'Numbers': [1234, 4, 333]})
print(df)
Letters Numbers
0 AB 1234
1 XY 4
2 ZW 333
df['Merged'] = df['Letters'] + df['Numbers'].astype(str).str.zfill(4)
print(df)
Letters Numbers Merged
0 AB 1234 AB1234
1 XY 4 XY0004
2 ZW 333 ZW0333
在 OP 评论说他具有floats
数值后进行编辑。
像 ChrisA 建议的那样,使用以下内容:
df['Merged'] = df['Letters'] + df['Numbers'].astype(int).astype(str).str.zfill(4)
print(df)
Letters Numbers Merged
0 AB 1234.0 AB1234
1 XY 4.0 XY0004
2 ZW 333.0 ZW0333
推荐阅读
- c# - Parallel.Foreach 是否可以安全地将值分配给目标列表项?
- r - gglpot中的2点图
- arrays - 如何对数组进行反向排序,排序从行尾开始
- php - 在 Domain.com 提供的共享主机上安装 Laravel 项目
- css - 删除 display:flex 会在链接周围添加空格。为什么?
- javascript - 使用 JavaScript 更改链接颜色属性
- raku - 在 Perl 6 中捕获 shell 命令的异常
- c - 使用 Map Reduce 的 POSIX 线程
- r - 在 RShiny 中使用 switch 选择 tibble 变量
- mongodb - 如何在不使用 javascript 的情况下在 bash 脚本中运行多个 mongo db 命令?