How to keep leading 0 when export pandas dataframe to csv?

Question:

I am exporting the data frame below to csv file in Python. The leading 0s are removed in the csv file.

      Name         ID
0     Bob          0245
1     Tina         2G5B

Both Name and ID values are strings in my pandas df.

I have no problem when re-opening the pandas df in Python with leading 0s after the df is saved by specifying dtype = 'str' in pd.read_csv.

However, I would like to open it in R using the read.csv command, the leading 0s will disappear.

If there is a way that I can save the csvs in Python with leading 0s showing up in the csv file. This problem could be solved.

Please advice.

Thanks!

Asked By: MAMS

||

Answers:

If we are. using R, then also use the colClasses argument from read.csv to read it as character else, otherwise it would automatically pick up the type of the columns from the values and read it as numeric

df1 <- read.csv("file.csv", colClasses = "character")
Answered By: akrun
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.