Changing The Name Of A DataFrame's Index In Pandas - SkyTowner

Changing a label of the index

To change the label of a specific index, use the DataFrame's rename(~) method.

Consider the following DataFrame:

df = pd.DataFrame({"A":[3,4],"B":[5,6]}, index=["a","b"])df A Ba 3 5b 4 6

Renaming specific index label

To rename row label from a to c:

df.rename(index={"a":"c"}) A Bc 3 5b 4 6

Renaming all index labels

To rename all the labels of the index:

df.index = ["c","d"]df A Bc 3 5d 4 6 Changing the name of Index

Single index case

Consider the following DataFrame:

df = pd.DataFrame({"A":[2,3],"B":[4,5]}, index=["a","b"])df A Ba 2 4b 3 5

To assign a name to a DataFrame's index:

df.index.name = "my_index"df A Bmy_indexa 2 4b 3 5

Multi-index case

Consider the following multi-index DataFrame:

index = [("A", "alice"), ("A", "bob"),("B", "cathy"),("B","david")]multi_index = pd.MultiIndex.from_tuples(index)df = pd.DataFrame({"age":[2,3,4,5],"height":[6,7,8,9]}, index=multi_index)df age heightA alice 2 6 bob 3 7B cathy 4 8 david 5 9

To change the name of both levels of the index:

df.index.names = ["group", "names"]df age height group names A alice 2 6 bob 3 7 B cathy 4 8 david 5 9

Tag » How To Name Index Pandas