how to set index as a certain column with .set_index() in python

To set a specific column as the index of a DataFrame in pandas, you can use the set_index() function. Here is an example:

main.py
import pandas as pd

# Create a DataFrame
data = {'Name': ['John', 'Emily', 'Michael', 'Emma'],
        'Age': [25, 30, 35, 28],
        'Country': ['USA', 'UK', 'Canada', 'USA']}

df = pd.DataFrame(data)

# Set the 'Name' column as the index
df = df.set_index('Name')
269 chars
12 lines

In this example, the 'Name' column is set as the index using set_index('Name'). The resulting DataFrame will have the 'Name' column as the index instead of the default integer index.

Note that the set_index() function returns a new DataFrame with the modified index. If you want to modify the DataFrame in place, you can pass the inplace=True argument:

main.py
df.set_index('Name', inplace=True)
35 chars
2 lines

This will modify the original DataFrame df and set the 'Name' column as the index.

related categories

gistlibby LogSnag