‘df.index.names’ return list of column names involved in a multi index.
Example
multi_index_column_names = df.index.names
multi_index_column_names.py
import pandas as pd
# Create a sample DataFrame
data = {'Year': [2020, 2020, 2020, 2021, 2021, 2021, 2022, 2022],
'Quarter': [1, 2, 3, 1, 2, 3, 1, 2],
'Sales': [100, 150, 115, 120, 180, 90, 130, 160],
'City': ['Bangalore', 'Bangalore', 'Bangalore', 'Hyderabad', 'Hyderabad', 'Hyderabad', 'Chennai', 'Chennai']
}
df = pd.DataFrame(data)
print('Original DataFrame\n', df)
# Set Year and Quarter as indexes
df.set_index(['Year', 'Quarter'], inplace=True)
print('\nAfter setting index columns Year and Quarter\n',df)
multi_index_column_names = df.index.names
print('\nmulti_index_column_names\n', multi_index_column_names)
Output
Original DataFrame Year Quarter Sales City 0 2020 1 100 Bangalore 1 2020 2 150 Bangalore 2 2020 3 115 Bangalore 3 2021 1 120 Hyderabad 4 2021 2 180 Hyderabad 5 2021 3 90 Hyderabad 6 2022 1 130 Chennai 7 2022 2 160 Chennai After setting index columns Year and Quarter Sales City Year Quarter 2020 1 100 Bangalore 2 150 Bangalore 3 115 Bangalore 2021 1 120 Hyderabad 2 180 Hyderabad 3 90 Hyderabad 2022 1 130 Chennai 2 160 Chennai multi_index_column_names ['Year', 'Quarter']
No comments:
Post a Comment