Change Column Names when Importing CSV File in Python (Example Code)

This article shows how to change the column names of a pandas DataFrame when importing a CSV file in Python.

Setting up the Example

import pandas as pd                           # Load pandas library
my_df = pd.DataFrame({'A':range(100, 105),    # Construct new pandas DataFrame
                      'B':[9, 3, 7, 1, 2],
                      'C':['a', 'f', 'c', 'f', 'f'],
                      'D':range(35, 30, - 1)})
print(my_df)
#      A  B  C   D
# 0  100  9  a  35
# 1  101  3  f  34
# 2  102  7  c  33
# 3  103  1  f  32
# 4  104  2  f  31
my_df.to_csv('my_df.csv')                     # Write exemplifying DataFrame to folder

Example: Modify Column Names when Loading a CSV File

my_df_new = pd.read_csv('my_df.csv',          # Import pandas DataFrame from CSV file
                        skiprows = 1,
                        names = ['var1', 'var2', 'var3', 'var4'])
print(my_df_new)
#    var1  var2 var3  var4
# 0   100     9    a    35
# 1   101     3    f    34
# 2   102     7    c    33
# 3   103     1    f    32
# 4   104     2    f    31

Further Resources & Related Tutorials

In addition, you might have a look at the other tutorials on my homepage. I have published numerous tutorials on similar topics such as lists and indices:

Leave a Reply

Your email address will not be published. Required fields are marked *

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