Modify header of an excel file using pandas

Viewed 441

I have an list of dates and I am trying to put that dates as a header of excel file. I have tried using Dataframe and dict but it's overwriting the file and employee names removed from the excel which I don't want. This is Sample excel Header Image:

Sample excel Header Image

and the following code:

dates = ['13-Dec', '20-Dec', '27-Dec', '03-Jan', '10-Jan']
df = pd.read_excel('C://Users//AMANSHAW//Desktop//color_it.xlsx')
df.columns = dates
df.rename(columns = dates , inplace=True)

Error:

TypeError: 'list' object is not callable

3 Answers

As stated in the Docs - you should better use a dictionary to be clear:

dates = {'A': '13-Dec', 'B': '20-Dec', 'C': '27-Dec', 'D': '03-Jan', 'E', '10-Jan'}
df = pd.read_excel('C://Users//AMANSHAW//Desktop//color_it.xlsx')
df.columns = dates
df.rename(columns = dates, inplace=True)

From the image you have attached, your data only has one column, so you won't directly be able to add headers to columns that don't exist. I suggest you do the following to add empty columns and give them the headers:

dates = ['13-Dec', '20-Dec', '27-Dec', '03-Jan', '10-Jan']
df = pd.read_excel('C://Users//AMANSHAW//Desktop//color_it.xlsx')
for date in dates:
    df[date] = np.nan   # or df[date] = ""

You can use reindex to add new empty columns

df = df.reindex(columns= df.columns.to_list() + dates)
Related