首页 > 解决方案 > 合并数据框的列并用零填充空数字

问题描述

我有一个带有两列的熊猫数据框,第一个标题为“字母”有两个字母(例如 AB),另一个标题为“数字”有数字(从 1 到 9999)。现在我想合并它们,使“Letters”= XY 和“Numbers”= 4 的第一行变为 XY0004,基本上确保两个单元格被合并,但数字单元格添加了额外的 0 零。带有 ZW 和 333 的第 2 行将变为 ZW0333。带有 AB 和 1234 的第 3 行将变为 AB1234。我怎样才能做到这一点?

标签: pythonpython-3.xpandas

解决方案


使用 pandasastype转换intstr使用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

推荐阅读