Assign Index¶
In [1]:
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()
Out[1]:
In [2]:
df.index = df.y
df
Out[2]:
set_index¶
In [21]:
import pandas as pd
df = pd.DataFrame(
{"month": [1, 4, 7, 10], "year": [2012, 2014, 2013, 2014], "sale": [55, 40, 84, 31]}
)
df
Out[21]:
In [22]:
df2 = df.set_index("month")
df2
Out[22]:
In [23]:
df2.columns
Out[23]:
In [7]:
df.year.iat[0]
Out[7]:
In [8]:
df.year.at[0]
Out[8]:
In [9]:
df2.year.iat[0]
Out[9]:
In [10]:
df2.year.at[1]
Out[10]:
In [24]:
df3 = df.set_index(["year", "month"])
df3
Out[24]:
In [16]:
import numpy as np
In [17]:
np.average([20000, 30000], weights=[9, 15])
Out[17]:
In [ ]: