I want to add the name of index of multi-index dataframe.
I want to set the name of red box in image as 'Ticker'
How can I do that?
To rename the multi index columns of the pandas dataframe, you need to use the set_levels() method. Use the below snippet to rename the multi level columns. where, ['b1','c1','d1'] - New column names of the index.
You can use the rename() method of pandas. DataFrame to change column/index name individually. Specify the original name and the new name in dict like {original name: new name} to columns / index parameter of rename() . columns is for the column name, and index is for the index name.
Pandas Series: rename() functionThe rename() function is used to alter Series index labels or name.
Creating a MultiIndex (hierarchical index) object A MultiIndex can be created from a list of arrays (using MultiIndex. from_arrays() ), an array of tuples (using MultiIndex. from_tuples() ), a crossed set of iterables (using MultiIndex. from_product() ), or a DataFrame (using MultiIndex.
Set index.names
(plural because MultiIndex
) or use rename_axis
:
df.index.names = ['Ticker','date']
#if want extract second name
df.index.names = ['Ticker',df.index.names[1]]
Or:
df = df.rename_axis(['Ticker','date'])
#if want extract second name
df = df.rename_axis(['Ticker',df.index.names[1]])
Sample:
mux = pd.MultiIndex.from_product([['NAVER'], ['2018-11-28','2018-12-01','2018-12-02']],
names=[None, 'date'])
df = pd.DataFrame({'open':[1,2,3]},
index=mux)
print(df)
open
date
NAVER 2018-11-28 1
2018-12-01 2
2018-12-02 3
df = df.rename_axis(['Ticker','date'])
print (df)
open
Ticker date
NAVER 2018-11-28 1
2018-12-01 2
2018-12-02 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With