I have a dataset in which some columns have header but the other ones don't have. Therefore, I want to add column name only to those who doesn't have column name. I know how to add column names using header but I would like to know how to do this using index so that I can add column names only to the empty ones. Any suggestions will be appreciated.


1 Answer 1


Loop through df.columns checking whether there is a column name or if it is empty:

import pandas as pd

# create df with two empty columns
df = pd.DataFrame({'a': [1,2], 'b': [1,2], 'c': [1,2], 'd':[1,2]})
df.columns = ['', 'b', '', 'd']

df with empty columns:

       b     d 
 0  1  1  1  1  
 1  2  2  2  2
# new of list columns names must be the same length as number of empty columns
empty_col_names = ['x', 'y']
new_col_names = []
count = 0

for item in df.columns:
    if item == '':
        count += 1

df.columns = new_col_names

df with filled columns:

    x  b  y  d
 0  1  1  1  1
 1  2  2  2  2
  • $\begingroup$ Yes it worked. Thank you for the help :) $\endgroup$
    – user94378
    Apr 10, 2020 at 9:07
  • $\begingroup$ You're welcome! Glad it helped $\endgroup$
    – Derek O
    Apr 10, 2020 at 9:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.