0

this question the reverse problem as In Python, how to specify a format when converting int to string?

here I have string "0001" to integer 1

string "0023" to integer 23

I wish to use this on pandas dataframe since I have column looks like:

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

I wish it become some thing like this

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

if I use int(001) or float(0023) it will gives me this error

SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers

Sway Wu
  • 379
  • 3
  • 8

4 Answers4

0

The best way is to use pd.to_numeric:

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

         UPCCode
0   783927275569
1  7839272755834
2     3485934573
3     6372792193
4     8094578237
NYC Coder
  • 7,424
  • 2
  • 11
  • 24
0

Here is a quick solution, just use the astype method:

>>> df = df.astype(int)
>>> df
         UPCCode
0   783927275569
1  7839272755834
2     3485934573
3     6372792193
4     8094578237
Grayrigel
  • 3,474
  • 5
  • 14
  • 32
0

If you want to apply this for column 'UPCCode' alone, do like this:

df = df['UPCCode'].astype(int)
Anjaly Vijayan
  • 237
  • 2
  • 9
-1

Hello I found some way to do that just try:

df["UPCCode"] = df["UPCCode"].str.strip("0")
df["UPCCode"] = df["UPCCode"].astype(int)
Barmar
  • 741,623
  • 53
  • 500
  • 612
Sway Wu
  • 379
  • 3
  • 8