1
$\begingroup$

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.

$\endgroup$
0
$\begingroup$

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 == '':
        new_col_names.append(empty_col_names[count])
        count += 1
    else:
        new_col_names.append(item)

df.columns = new_col_names

df with filled columns:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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