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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With