【问题标题】:Add leading zeroes only if it begin with digit in pandas dataframe只有在熊猫数据框中以数字开头时才添加前导零
【发布时间】:2021-04-12 11:59:54
【问题描述】:

我有一个包含特殊字符和数字的数据框列。只有当它以数字开头时,我才希望有前导零。我总共需要 3 位数字。 我尝试了以下代码:

df['input'] = df['input'].str.zfill(3)

输入:

column
1
$500
333
2
(8
?8
5
1
444

输出:

column
001
$500
333
002
(8
?8
005
001
444

【问题讨论】:

  • 目前尚不清楚您要完成什么。我建议张贴更清晰的表示您的输入和输出的内容。
  • 请添加更多示例
  • 我的数据框列包含上述输入和输出。如果值以数字开头并且如果它以特殊字符开头,我希望有前导 0,它可以忽略添加 0。我总共需要 3 位数字,包括 0。
  • 只需使用带有掩码的zfill(3)。可以使用isdigit() 计算掩码。详情查看我的回答

标签: python pandas


【解决方案1】:

这是使用zfill 和掩码的优雅方式。

df = pd.DataFrame({'strings':['1','$500','333','2','(8','?8','5','1','444']})

#Mask for checking if first alphabet is digit
mask = df.strings.str[0].str.isdigit()

#Apply zfill on values where mask is True
df.loc[mask, 'strings'] = df.strings.str.zfill(3)
print(df)
  strings
0     001
1    $500
2     333
3     002
4      (8
5      ?8
6     005
7     001
8     444

【讨论】:

  • 更新了虚拟数据的可重复性。
  • 谢谢阿克谢。
  • 你能帮忙解决这个问题吗? stackoverflow.com/questions/65605150/…
  • @Karthikchengalvarayan,使用 apply 效率非常低。如果上述方法不清楚,请告诉我,因为使用 str 方法明显更好,更易读。
【解决方案2】:
import pandas as pd

df = pd.DataFrame(['1','$500','333','2','(8','?8','5','1','444'], columns=['input'])

# Contains uses regex.
ix = df['input'].str.contains('^[0-9]')
df.loc[ix, 'input'] = df.loc[ix, 'input'].str.zfill(3)
df

>>>  input
0   001
1  $500
2   333
3   002
4    (8
5    ?8
6   005
7   001
8   444

【讨论】:

    【解决方案3】:

    你可以通过以下方式得到你想要的:

    df_merge['output'] = df_merge['input'].apply(lambda x : f'{x:0>3}' if x[0] in '0123456789' else x)
    

    验证

    假设下面的例子来模拟你给出的案例:

    import pandas as pd
    df_merge = pd.DataFrame({'input':['1','$500','333','2','(8','?8']})
    

    打印(df_merge['input'])

    0       1
    1    $500
    2     333
    3       2
    4      (8
    5      ?8
    Name: input, dtype: object
    

    现在申请:

    df_merge['output'] = df_merge['input'].apply(lambda x : f'{x:0>3}' if x[0] in '0123456789' else x)
    

    打印(df_merge['输出'])

    0     001
    1    $500
    2     333
    3     002
    4      (8
    5      ?8
    Name: output, dtype: object
    

    祝你好运

    【讨论】:

    • 感谢您的回答。这是在做什么 f'{x:0>3}'。 ?
    • 第一:感谢accepting my answer voting up - 第二:关于`f'{x:0>3} ', x` 是对输入值的引用,0 是要填充的字符,>3 表示用 '0' 完成输入,最多 3 个字符。
    • 你能回答下面的问题吗:stackoverflow.com/questions/65605150/…
    • 欢迎您,我会说,但是您在这里接受我的回答了吗?您刚刚投票但未接受。
    【解决方案4】:

    使用映射和函数将数值填零

    df = pd.DataFrame({'strings':['1','$500','333','2','(8','?8','5','1','444']})
    
    def zero_pad(x):
        if x.isdigit():
            return x.zfill(3)
        else:
           return x
    
    df['strings']=df['strings'].map(zero_pad)
    print(df)
    

    输出 字符串

    0     001
    1    $500
    2     333
    3     002
    4      (8
    5      ?8
    6     005
    7     001
    8     444
    

    【讨论】:

      猜你喜欢
      • 2013-09-15
      • 2017-09-09
      • 2020-05-30
      • 1970-01-01
      • 2018-10-06
      • 2022-09-24
      • 2018-05-10
      • 1970-01-01
      相关资源
      最近更新 更多