You can set the index in Pandas with any of the following methods. I highly recommend you This book to learn Python.
Step 1: Install Pandas Library
Install the Pandas library using this code, if it is not installed.
pip install pandas
Method 1
# Import the Pandas library as pd
import pandas as pd
# Initialize a dictionary
dict = {'Students':['John', 'Harry', 'Hasan', 'Chris'],
'Scores':[84, 73, 93, 85]}
# Create DataFrame from dictionary
df = pd.DataFrame(dict, index=['A', 'B','C','D'])
# Display the DataFrame
print(df)Output:
Students Scores A John 84 B Harry 73 C Hasan 93 D Chris 85
Method 2
# Import the Pandas library as pd
import pandas as pd
# Initialize a dictionary
dict = {'Students':['John', 'Harry', 'Hasan', 'Chris'],
'Scores':[84, 73, 93, 85],
'Alphabets':['A', 'B', 'C', 'D']}
# Create DataFrame from dictionary
df = pd.DataFrame(dict)
# Display DataFrame
print(df)
df = df.set_index('Alphabets')
# Display the DataFrame
print(df)Output:
Students Scores Alphabets
0 John 84 A
1 Harry 73 B
2 Hasan 93 C
3 Chris 85 D
Students Scores
Alphabets
A John 84
B Harry 73
C Hasan 93
D Chris 85


