This content originally appeared on CodeSource.io and was authored by Ariessa Norramli
In this article, you will learn how to set a column as an index in Python.
Let’s say you have a DataFrame of food.
# Import pandas module
import pandas as pd
# Create DataFrame
df = pd.DataFrame({"Name": ['Pizza', 'Burger', 'Waffle'],
"Price ($)": [10, 5, 6],
"Availability": [True, False, True],
"Delivery": [True, True, True],
"Pickup": [True, True, False]})
Set Column As Index in Python
In order to set a column as an index, you can use the DataFrame.set_index()
method.
# Import pandas module
import pandas as pd
# Create DataFrame
df = pd.DataFrame({"Name": ['Pizza', 'Burger', 'Waffle'],
"Price ($)": [10, 5, 6],
"Availability": [True, False, True],
"Delivery": [True, True, True],
"Pickup": [True, True, False]})
# Set column "Name" as index column
df.set_index("Name", inplace = True)
# Display DataFrame
print(df)
Note: The DataFrame.set_index()
method functions by setting the supplied column name as index column. The inplace
parameter functions by making the changes if the supplied column name exists in DataFrame.
The post How to Set Column As Index in Python appeared first on CodeSource.io.
This content originally appeared on CodeSource.io and was authored by Ariessa Norramli
Ariessa Norramli | Sciencx (2021-02-25T10:55:07+00:00) How to Set Column As Index in Python. Retrieved from https://www.scien.cx/2021/02/25/how-to-set-column-as-index-in-python/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.