• Post author:
  • Post category:Pandas
  • Post last modified:March 27, 2024
  • Reading time:15 mins read
You are currently viewing How to Rename Column by Index in Pandas

How to rename column by index in pandas? You can rename pandas DataFrame column name by index (position) using rename() method or by assigning column name to df.columns.values[index]. In this article, I will explain renaming column names by index on pandas DataFrame with examples.

Advertisements

1. Quick Examples of Rename Column by Index

If you are in a hurry, below are some quick examples of how to change column names by index on Pandas DataFrame.


# Quick examples of rename column by index

# Example 1: Assign column name by index
df.columns.values[1] = 'Courses_Fee'
print(df.columns)

# Example 2: Rename column name by index
df.rename(columns={df.columns[2]: 'Courses_Duration'},inplace=True)
print(df.columns)

# Example 3: Rename multiple columns
df.rename(columns={df.columns[1]: 'Fee', df.columns[2]: 'Duration'},inplace=True)
print(df.columns)

Now, let’s create a DataFrame with a few rows and columns, execute these examples, and validate the results. Our DataFrame contains column names Courses, Fee, Duration, and Discount.


# Create DataFrame
import pandas as pd
technologies = [ ["Spark",20000,"30days"], 
                 ["Pandas",25000,"40days"], 
               ]
column_names=["Courses","Fee",'Duration']
df=pd.DataFrame(technologies, columns=column_names)
print("Create DataFrame:\n",df.columns)

Yields below column names.

pandas rename column index

2. Rename Column Name by Index

If you want to rename a single column by Index on pandas DataFrame then you can just assign a new value to the df.columns.values[idx], replace idx with the right index where you wanted to rename.

This program first assigns the value ‘Courses_Fee’ to the element at index 1 of the df.columns.values array, effectively renaming the column at index 1 in the DataFrame. The print(df.columns) line then outputs the updated column names.


# Assign column name for Index
df.columns.values[1] = 'Courses_Fee'
print(df.columns)

Yields below output. df.columns get the column names as a list from pandas DataFrame.


# Output:
Index(['Courses', 'Courses_Fee', 'Duration'], dtype='object')

This changes the column name from Fee to Courses_Fee.

3. Using rename() to Change Column Name at Index

You can also use pandas DataFrame.rename() method to change column name at a specific index. This method takes the columns param with value as dict (key-value pair). The key is an existing column name and the value would be a new column name. Though this method doesn’t support by index, we can get the column name of the index by using df.columns[index].

This program renames the column at index 2 (column ‘Duration’) to ‘Courses_Duration’ using the rename method with the columns parameter. The inplace=True argument modifies the original DataFrame in place. The print(df.columns) line then outputs the updated column names.


# Rename single column by index
df.rename(columns={df.columns[2]: 'Courses_Duration'},inplace=True)
print(df.columns)

Yields below output. Use inplace=True to replace on existing DataFrame object. not using this it returns a new DF without changing on an existing one.


# Output:
Index(['Courses', 'Courses_Fee', 'Courses_Duration'], dtype='object')

This changes the column name from Duration to Courses_Duration.

4. Rename Multiple Columns by Index

Now let’s see how to rename multiple column names by index/position in pandas DataFrame. For this, I will be using the same method explained above. To rename multiple, you have to pass multiple mappings in key-value pair to the columns param.


# Rename multiple columns by Index
df.rename(columns={df.columns[1]: 'Fee', df.columns[2]: 'Duration'},inplace=True)
print(df.columns)

Yields below output.


# Output:
Index(['Courses', 'Fee', 'Duration'], dtype='object')

The above example renames the multiple columns to the original values.

5. Complete Example


# Import pandas library
import pandas as pd
technologies = [ ["Spark",20000, "30days"], 
                 ["Pandas",25000, "40days"], 
               ]]

# Create DataFrame
column_names=["Courses","Fee",'Duration']
df=pd.DataFrame(technologies, columns=column_names)
print(df.columns)

# Assign column name by index
df.columns.values[1] = 'Courses_Fee'
print(df.columns)

# Rename column name by index
df.rename(columns={df.columns[2]: 'Courses_Duration'},inplace=True)
print(df.columns)

# Rename multiple columns
df.rename(columns={df.columns[1]: 'Fee', df.columns[2]: 'Duration'},inplace=True)
print(df.columns)

Frequently Asked Questions on Rename Column by Index in Pandas?

How can I rename a column by index in pandas?

To rename a column by index in pandas, you can use the rename method along with the columns parameter. For example, the rename method is used with the columns parameter to specify the mapping of the old column name to the new column name. The inplace=True argument modifies the original DataFrame in place. Replace index_to_rename with the index of the column you want to rename, and provide the desired new column name.

What does the inplace=True parameter do?

The inplace=True parameter in pandas is used to perform operations directly on the original object (DataFrame or Series) without the need to assign the result back to a new variable. When inplace=True is specified, the modifications are applied directly to the existing object, and the object is updated in memory.

Is there an alternative way to rename a column by index?

An alternative way to rename a column by index in pandas is to use the set_axis method. The set_axis method allows you to set the index or column labels along a specified axis.

Can I rename multiple columns at once using index?

You can rename multiple columns at once using their indices in pandas. You can provide a dictionary with the mappings of old column names (specified by their indices) to new column names in the rename method.

Can I rename columns based on certain conditions?

You can rename columns based on certain conditions in pandas using the rename method along with a mapping dictionary or a function. For example, the column_mapping dictionary is defined, and it specifies that if the column name contains ‘A’, it should be renamed to ‘New_A’. You can adjust the conditions in the dictionary according to your specific requirements.

How do I rename columns without specifying the new names directly?

If you want to rename columns without specifying the new names directly, you can use a function or another mechanism to generate the new column names dynamically.

Conclusion

In this article, you have learned to rename column names by index using the rename() method and df.columns.values[idx]. By using the rename() method you can also change single and multiple columns, for multiples you need to create a map with a key-value pair for all columns you want to change.

References