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!
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")
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!
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")