Skip to content
Advertisement

Trying to keep the same type after saving a dataframe in a csv file

When I try to get my dataframe out of the csv file the type of the data changed. Is there a way I can avoid this?

example

Advertisement

Answer

csv files does not have a datatype definition header or something similar. So when your read a csv pandas tries to guess the types and this can change the datatypes. You have two possibile solutions:

  1. Provide the datatype list when you do read_csv with dtype and parse_dates keywords (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html)
  2. Use a different file format that store data with a schema (ex parquet)

for example:

JavaScript

that output:

JavaScript
Advertisement