Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Change the Index of a pandas DataFrame

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

Assign Index

import pandas as pd

df = pd.DataFrame(
    {"x": [1, 2, 3, 4, 5], "y": [5, 4, 3, 2, 1]}, index=["r1", "r2", "r3", "r4", "r5"]
)

df.head()
Loading...
df.index = df.y
df
Loading...

set_index

import pandas as pd

df = pd.DataFrame(
    {"month": [1, 4, 7, 10], "year": [2012, 2014, 2013, 2014], "sale": [55, 40, 84, 31]}
)
df
Loading...
df2 = df.set_index("month")
df2
Loading...
df2.columns
Index(['year', 'sale'], dtype='object')
df.year.iat[0]
2012
df.year.at[0]
2012
df2.year.iat[0]
2012
df2.year.at[1]
2012
df3 = df.set_index(["year", "month"])
df3
Loading...
import numpy as np
np.average([20000, 30000], weights=[9, 15])
26250.0