0

I load data to dataframe:

dfzips = pd.read_excel(filename_zips, dtype='object')

Dataframe has column with value: 00590

After load dataframe I got this as 590.

I have tried dtype='object'. Does not help me.

Mamed
  • 15
  • 4
  • Does this answer your question? [Pandas read\_csv dtype leading zeros](https://stackoverflow.com/questions/16929056/pandas-read-csv-dtype-leading-zeros) – G. Anderson May 27 '22 at 17:29
  • In Excel 00590 could still be a numeric value that is displayed with leading zeros. So when loaded into a DF it would take the value. Double check that in the spreadsheet. – jch May 27 '22 at 17:30
  • I load excel file, the answer in comment did not help me – Mamed May 27 '22 at 17:33

2 Answers2

0

This is the well known issue in pandas library.

try below code :

dfzips = pd.read_excel(filename_zips, dtype={'name of the column': pd.np.str})

Or:

try writing converters while reading excel.

example : df = pd.read_excel(file, dtype='string', header=headers, converters={'name of the column': decimal_converter})

function decimal_converter:

def decimal_converter(value):

try:

    return str(float(value))

except ValueError:

    return value

converters={'column name': function}

You can modify converter function according to your requirement.

Try above solutions. I hope it should work. Good Day

  • First deprecated, the second in which type convert? – Mamed May 27 '22 at 17:39
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 28 '22 at 04:27
0

Have you tried using str instead of object? if you use str (string) it maintains the zeros at the beginning.

It could be good to specify the column name you would like to change to str or object (without quotations).

1)

dfzips = pd.read_excel(filename_zips,dtype=str)

It even supports this a dict mapping where the keys constitute the column names and values the data types to be set when you want to change it. You didnt specify the column name so i just put it as "column_1"

dfzips = pd.read_excel(filename_zips,dtype={"column_1":str})
fiddy
  • 76
  • 4