Set Data Type when Importing pandas DataFrame from CSV File in Python (Example Code)

This article shows how to manually set the data type for variables in a CSV file in the Python programming language.

Setting up the Example

import pandas as pd                       # Import pandas library in Python
my_df = pd.DataFrame({'A':range(1, 5),    # Construct new pandas DataFrame
                      'B':['a', 'c', 'a', 'b'],
                      'C':range(15, 11, - 1)})
print(my_df)
#    A  B   C
# 0  1  a  15
# 1  2  c  14
# 2  3  a  13
# 3  4  b  12
my_df.to_csv('my_df.csv')                 # Write exemplifying DataFrame to folder

Example: Specify Classes of pandas DataFrame Columns when Reading a CSV File

my_df_new = pd.read_csv('my_df.csv',      # Read CSV file
                        dtype = {'A': int, 'B': str, 'C': int})

Further Resources & Related Articles

In addition, you may want to have a look at the related Python tutorials on this website. I have published numerous tutorials already:

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top