【问题标题】:In python, how to convert sting to int, (those string might begin with 0)在python中,如何将字符串转换为int,(那些字符串可能以0开头)
【发布时间】:2020-09-10 20:01:16
【问题描述】:

这个问题是相反的问题 In Python, how to specify a format when converting int to string?

这里我有字符串“0001”到整数 1

字符串“0023”转整数23

我希望在 pandas 数据框上使用它,因为我的列看起来像:

dic = {'UPCCode': ["00783927275569", "0007839272755834", "003485934573", "06372792193", "8094578237"]}
df = pd.DataFrame(data=dic)

我希望它变成这样

dic = {'UPCCode': [783927275569, 7839272755834, 3485934573, 6372792193, 8094578237]}
df = pd.DataFrame(data=dic)

如果我使用 int(001) 或 float(0023) 它会给我这个错误

SyntaxError:十进制整数文字中的前导零是不允许的;对八进制整数使用 0o 前缀

【问题讨论】:

  • 试试df['UPCCode'] = df['UPCCode'].astype(int)
  • int("00783927275569") 完全有效

标签: python pandas dataframe


【解决方案1】:

最好的方法是使用pd.to_numeric

df['UPCCode'] = pd.to_numeric(df['UPCCode'])
print(df)

         UPCCode
0   783927275569
1  7839272755834
2     3485934573
3     6372792193
4     8094578237

【讨论】:

    【解决方案2】:

    您好,我找到了一些方法来尝试:

    df["UPCCode"] = df["UPCCode"].str.strip("0")

    df["UPCCode"] = df["UPCCode"].astype(int)

    【讨论】:

      【解决方案3】:

      这是一个快速的解决方案,只需使用astype 方法:

      >>> df = df.astype(int)
      >>> df
               UPCCode
      0   783927275569
      1  7839272755834
      2     3485934573
      3     6372792193
      4     8094578237
      

      【讨论】:

        【解决方案4】:

        如果您想单独将其应用于“UPCCode”列,请执行以下操作:

        df = df['UPCCode'].astype(int)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-04-28
          • 2011-04-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-04-24
          • 2015-11-12
          相关资源
          最近更新 更多