Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to I export data with leading zeros from Pandas to CSV preserving the leading zeros in csv

I have a pandas data frame in which one column contains data with leading zeros.I want to export the data frame in CSV by preserving leading zeros. So I tried following code

import numpy as np
import pandas as pd
import os
os.chdir(path)
x=np.array(['0134','0567','0012','0009'])

df=pd.DataFrame(x,columns=['Test'])
df.dtypes
df.Test=df.Test.astype("str")
df.to_csv("leadingZero.csv")

But in leadingZero.csv I'm finding 0's in one column & number discarded zeros in another column

Can you guide me how do I preserve leading zeros in CSV?

like image 754
Sonia Avatar asked Oct 19 '25 11:10

Sonia


1 Answers

The issue here is with csv file. If you open csv file using different formats like wordpad, notepad, etc., leading zeros will appear

Use apply('="{}".format) on the column where you want to preserve the leading zeros

import pandas as pd
df = pd.DataFrame({'Test': ['0134','0567','0012','0009']})
df['Test'] = df['Test'].apply('="{}"'.format)
df.to_csv('withLeadingZeros'+'.csv', index = False)

output from withLeadingZeros.csv

enter image description here

like image 151
Govinda Avatar answered Oct 21 '25 09:10

Govinda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!