C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Set IndexPandas set index() is used to set a List, Series or DataFrame as index of a Data Frame. We can set the index column while making a data frame. But sometimes a data frame is made from two or more data frames and then index can be changed using this method. Syntax: DataFrame.set_index(self, keys, drop=True, append=False, inplace=False, verify_integrity=False) Parameters:
It can be either a single column key, a single array of the same length as the calling DataFrame, or also a list that contains an arbitrary combination of column keys and arrays.
It checks whether append the columns to an existing index.
It is used to modify the DataFrame in place. We don't need to create a new object.
It checks the new index for duplicate values. Otherwise, it will defer the check until necessary. It also set it to False that will improve the performance of this method. Returns: It will change the row labels as the output. Example1:This example shows how to set the index: import pandas as pd info = pd.DataFrame({'Name': ['William', 'Phill', 'Parker', 'Smith'], 'Age': [32, 38, 41, 36], 'id': [105, 132, 134, 127]}) info Output: Name Age id 0 William 32 105 1 Phill 38 132 2 Parker 41 134 3 Smith 36 127 Now, we have to set the index to create the 'month' column: info.set_index('month') Output: Age id Name William 32 105 Phill 38 132 Parker 41 134 Smith 36 127 Example2:Create a MultiIndex using columns 'Age' and 'Name': info.set_index(['Age', 'Name']) Output: Name id Age 32 William 105 38 Phill 132 41 Parker 134 36 Smith 127 Example3:It creates a MultiIndex using an Index and a column: info.set_index([pd.Index([1, 2, 3, 4]), 'Name']) Output: Age id Name 1 William 32 105 2 Phill 38 132 3 Parker 41 134 4 Smith 36 127 Example4:Create a MultiIndex using two Series: a = pd.Series([1, 2, 3, 4]) info.set_index([a, a**2]) Output: Name Age id 1 1 William 32 105 2 4 Phill 38 132 3 9 Parker 41 134 4 16 Smith 36 127
Next TopicPandas NumPy
|