Pandas DataFrame set_index() Method
Example
Make the "name" column become the index of the DataFrame:
import pandas as pd
data = {
"name": ["Sally", "Mary",
"John", "Monica"],
"age": [50, 40, 30, 40],
"qualified":
[True, False, False, False]
}
df = pd.DataFrame(data)
newdf
= df.set_index('name')
Try it Yourself »
Definition and Usage
The set_index()
method allows one or more
column values become the row index.
Syntax
dataframe.set_index(keys, drop, append, inplace, verify_integrity)
Parameters
The drop
, append
,
inplace
,
verify_integrity
parameters are
keyword arguments.
Parameter | Value | Description |
---|---|---|
keys | Required. String or list containing column labels and/or column keys | |
drop | True |
Optional, default True. Set to False the column you set as row index, should still be kept as a column |
append | True |
Optional, default False. Set to True if the new row index should be appended to the existing (by default the existing index gets overwritten) |
inplace | True |
Optional, default False. If True: the operation is done on the current DataFrame. If False: returns a copy where the operation is done. |
verify_integrity | True |
Optional, default False. Specifies if the new indexes should be checked for duplicates or not |
Return Value
A DataFrame with the result, or None if the inplace parameter is set to True.
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.