Pandas >> Index

2022-08-01 Pandas

Table of Contents

In this article, we will show you some examples about Pandas DataFrame Index.

Pandas GroupBy

Pandas DataFrame index to column

# Prepare the data
import pandas as pd

df = pd.DataFrame({'A': ["a", "b", "c", "d"],
                   'B': [10, 20, 30, 40],
                   'C': [100, 200, 300, 400]})
df

Pandas

df2 = df.reset_index()
# OR Directly change the df
df.reset_index(inplace=True)

Pandas

Change the index to column and rename its column name

df2 = df.reset_index().rename(columns={'index':'my_index'})
# OR 
df2 = df.reset_index()
df2.index.name = 'my_index'

df2

Pandas

Pandas DataFrame column to index

df2 = df.set_index('A')
df2

Pandas

Pandas DataFrame get Index name

df2.index.name

'A'

Pandas DataFrame Index to array

df2.index.values

array([‘a’, ‘b’, ‘c’, ’d'], dtype=object)

Pandas DataFrame Index to list

df2.index.tolist()

[‘a’, ‘b’, ‘c’, ’d']

Pandas DataFrame Index start from 1

# Reset the index and add 1 to it to start from 0
df2.index = df2.reset_index().index + 1
df2

Pandas

Pandas DataFrame Index of max value

Get the index of the max value of all columns

df2.idxmax()

Pandas

Get the index of the max value in the specified column

df2.idxmax()["B"]

4

Get the row by the above index

df2.loc[df2.idxmax()["B"]]

Pandas

Subscribe and be the FIRST reader of our latest articles

* indicates required

Contact us