首页 > 解决方案 > 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() 的原因。

这个问题不同,因为我需要避免填充字母字符串。

标签: pythonpandas

解决方案


使用可以从选择带有数字的行开始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

推荐阅读