简体   繁体   中英

Add leading zeros to a column

I have a data column containing phone numbers

where pandas automatically remove leading zeros from phone numbers upon reading the file.

I couldn't change that behavior, However I tried to add the leading zeros instead.

So I tried this:

 # add the missing leading zeros to phone numbers.
 read_file['Phone 1 - Value'] = "0" + read_file['Phone 1 - Value'].astype(str)
 print(read_file.head())

But it also didn't work, the strange thing is that when printing the head() it actually works, but when saving the file as a CSV file later on it defaults back to that odd behavior as shown below:

read_file.to_csv(export_file_path, index = None, header=True, index_label = True, encoding='utf-8')

Any tips?

I think here is problem how pandas read numbers.

In file are leading zeros, but pandas convert values to integers, so removed.

For avoid it convert column to strings by dtype parameter in read_csv :

df = pd.read_csv(export_file_path, dtype={'Phone 1 - Value':str})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM