Sometimes we want to change the labels for rows and columns of a DataFrame. For example, after creating a DataFrame from a Python list or after reading a CSV file, we may want to change the labels for a specific row or a column of the DataFrame, or we may want to change the labels for all the rows and columns of the DataFrame. We can do so using the DataFrame.rename() function.
import pandas list1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] df1 = pandas.DataFrame(list1) print(df1) df1.rename(index={0:"Row 1", 1:"Row 2", 2:"Row 3"}, columns={0:"Column 1", 1:"Column 2", 2:"Column 3"}, inplace=True) print(df1)
Here, we are first creating a DataFrame df1 from a Python list list1. If we print df1, it will show:
0 1 2 0 1 2 3 1 4 5 6 2 7 8 9
Here, we have not provided any labels for the rows and columns of the DataFrame yet. So, the output shows default labels for the rows and columns, that start from 0.
Now, we are renaming the labels of the DataFrame using the DataFrame.rename() function.
df1.rename(index={0:"Row 1", 1:"Row 2", 2:"Row 3"}, columns={0:"Column 1", 1:"Column 2", 2:"Column 3"}, inplace=True)
Here, the parameter indexes refers to the labels for the rows and the parameter columns refers to the labels for the columns. So, we are renaming …






0 Comments