Change Name of pandas DataFrame Column by Index in Python (Example Code)
In this post you’ll learn how to change the names of pandas DataFrame columns by index positions in Python programming.
Setting up the Example
import pandas as pd # Import pandas library in Python |
import pandas as pd # Import pandas library in Python
my_df = pd.DataFrame({'A':range(1, 6), # Construct pandas DataFrame 'B':['y', 'w', 'r', 't', 'f'], 'C':range(11, 16), 'D':range(10, 15)}) print(my_df) # A B C D # 0 1 y 11 10 # 1 2 w 12 11 # 2 3 r 13 12 # 3 4 t 14 13 # 4 5 f 15 14 |
my_df = pd.DataFrame({'A':range(1, 6), # Construct pandas DataFrame 'B':['y', 'w', 'r', 't', 'f'], 'C':range(11, 16), 'D':range(10, 15)}) print(my_df) # A B C D # 0 1 y 11 10 # 1 2 w 12 11 # 2 3 r 13 12 # 3 4 t 14 13 # 4 5 f 15 14
Example: How to Modify the Name of pandas DataFrame Column by Index
df_rename = my_df.rename(columns = {my_df.columns[1]: 'XXX'}) # Change column name print(df_rename) # A XXX C D # 0 1 y 11 10 # 1 2 w 12 11 # 2 3 r 13 12 # 3 4 t 14 13 # 4 5 f 15 14 |
df_rename = my_df.rename(columns = {my_df.columns[1]: 'XXX'}) # Change column name print(df_rename) # A XXX C D # 0 1 y 11 10 # 1 2 w 12 11 # 2 3 r 13 12 # 3 4 t 14 13 # 4 5 f 15 14
Related Articles & Further Resources
Here, you may find some additional resources that are similar to the topic of this post.