2

When importing .xlsx using pd.read_excel(), how can I change the column names partially?

For example, Excel document data.xlsx consists of 99 columns, like col_1, col_1, col_3 .... col_99.

I'd like to only rename like the dictionary rename = {'col_1' : 'ID', 'col_2' : 'name', 'col_3' : 'score'}

As for the other columns col_4 ~ col_99, there isn't any need to rename them.

pd.read_excel('data.xlsx') has the option names = [], but it needs the entire column names to be overwritten.

Is there another way to only change some of the column names, when using pd.read_excel()?

0

1 Answer 1

1

At this point, vanilla pd.read_excel will only allow you to rename all columns with parameter "names". You can pass a List of column names to the function. If all column names are known, replace the ones you want to rename and keep the other names in the list the same, so that they don't change in the process of creating your dataframe:

import pandas as pd

colnames = ['Col1', 'Col2','Col3']

xldf = pd.read_excel(r'YourPath\test.xlsx', names= colnames)

To rename specific columns, you can use the following syntax after you have created your dataframe out of your Excel document:

xldf.rename(columns={'Col1':'NewCol1'}, inplace=True)

If you want it all in one function call, you can combine the two ideas and write your own pd.read_excel "extension". This one uses a List of column names and the indexes to read in the .csv file and renames them in one function:

import pandas as pd
path = r'YourPath\test.xlsx'

   def readWithOwnNames(path,indexes,names):
   xlpd =pd.read_excel(path)
   xlpd.columns.values[indexes] = names
   return xlpd

 df = readWithOwnNames(path,[0,1,2],['Col1', 'Col2','Col3'])

A Dictionary would also be an option if you prefer that as your input:

import pandas as pd
path = r'YourPath\test.xlsx'

def readWithOwnNames(path,dict):
    xlpd =pd.read_excel(path)
    for i in dict:
        xlpd.columns.values[i] = dict[0]

    return xlpd

df = readWithOwnNames(path,{0: "Col1", 1: "Col2", 2: "Col3"})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.