如何在合并Pandas DataFrame列时保留左侧前导零?
问题:合并DataFrame多列为保留前置0的字符串列
我需要将DataFrame中的F、S、P三列合并为一列FSP,要求保留所有原始数字(包括开头的0)。
示例DataFrame
| F | S | P |
|---|---|---|
| 0 | 1 | 2 |
| 0 | 1 | 4 |
| 0 | 0 | 14 |
| 0 | 0 | 25 |
| 0 | 2 | 5 |
现有代码
df['FSP']=df['F'].map(str)+df["S"].map(str)+df["P"].map(str)
当前输出
| F | S | P | FSP |
|---|---|---|---|
| 0 | 1 | 2 | 12 |
| 0 | 1 | 4 | 14 |
| 0 | 0 | 14 | 14 |
| 0 | 0 | 25 | 25 |
| 0 | 2 | 5 | 25 |
期望输出
| F | S | P | FSP |
|---|---|---|---|
| 0 | 1 | 2 | 012 |
| 0 | 1 | 4 | 014 |
| 0 | 0 | 14 | 0014 |
| 0 | 0 | 25 | 0025 |
| 0 | 2 | 5 | 025 |
解决方案
你的问题源于字符串拼接时数据类型转换不彻底,导致前置0丢失。以下几种方法均可解决:
方法1:用astype(str)明确转换类型
df['FSP'] = df['F'].astype(str) + df['S'].astype(str) + df['P'].astype(str)
方法2:用apply逐行格式化拼接
df['FSP'] = df.apply(lambda x: f"{x['F']}{x['S']}{x['P']}", axis=1)
方法3:用str.cat方法批量拼接
df['FSP'] = df['F'].astype(str).str.cat([df['S'].astype(str), df['P'].astype(str)])
以上方法都能确保每列数值完整转为字符串后拼接,保留所有原始数字(包括开头的0),得到目标格式。
内容的提问来源于stack exchange,提问作者asmaa mahmoud
相关产品推荐
相关产品推荐

