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
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