python - Pandas - zfill 混合列中的仅数值
问题描述
我的数据框中有两列包含混合字符串 - 有些全是字母,有些全是数字。我需要用前导零填充数字字符串,而不是字母字符串。
输入:
Item
0 571
1 63
2 12345
3 99561
4 lid
5 show
期望的输出:
Item
0 00571
1 00063
2 12345
3 99561
4 lid
5 show
这是我到目前为止所得到的:
item_columns = ['Item','Item_num']
for column in item_columns:
df[column][df[column].notnull()] = df[column].astype(str).str.zfill(5)
输出是:
Item
0 00571
1 00063
2 12345
3 99561
4 00lid
5 0show
我不能在索引 4 和 5 上使用前导零。注意:我还需要保留 NaN,以便它们将作为 NULL 加载到数据库中,这就是我在进行转换之前检查 notnull() 的原因。
与这个问题不同,因为我需要避免填充字母字符串。
解决方案
使用可以从选择带有数字的行开始isdecimal
:
print(df)
Item
0 571
1 63
2 12345
3 99561
4 lid
5 show
df['Item'][df['Item'].str.isdecimal()] = df['Item'][df['Item'].str.isdecimal()].str.zfill(5)
print(df)
Item
0 00571
1 00063
2 12345
3 99561
4 lid
5 show
推荐阅读
- python - 如何从csv中读取列名作为pandas中的整数
- python - 当该元素是列表时,如何从列表中删除该元素?
- python - While 循环在 1 次迭代后停止并且不删除所有值
- javascript - 你能在一次绘制调用中多次重用一个小的 WebGL 缓冲区吗?
- reactjs - 悬停 MUI 上的下划线动画
- python - 如何按键拆分字典列表
- powershell - Powershell:Start-Process 不会将参数传递给 cmd.exe
- python - 有没有办法让 Class[key] 工作以从静态容器中提取?
- kubernetes - Kubernetes:如何将 Promtail 设置为 sidecar 以读取自定义日志路径
- ios - 如何在 iOS 上安装和首次运行期间跟踪是否更新文件