In this article we will discuss how to get column names or Row Index names in DataFrame object.

First of all, create a dataframe object of students records i.e.

Contents of DataFrame objects are as follows,

Now let’s access column names and Row indexes,

Accessing & Modifying Column Names in DataFrame

Get all column names from DataFrame

DataFrame object has an Attribute columns that is basically an Index object and contains column Labels of Dataframe. We can get the ndarray of column names from this Index object i.e.

Its contents will be,

Get Column name by Index / position in DataFrame

As df.column.values is a ndarray, so we can access it contents by index too. So, let’s get the name of column at index 2 i.e.

Changing the name of a Column in DataFrame

Any modification in this ndArray (df.column.values) will modify the actual DataFrame. For example let’s change the name of column at index 0 i.e.

This change will be reflected in linked DataFrame object too. Now contents of DataFrame object is,

But we convert it to list before modifying then changes will not be reflected in original DataFrame object.

For example create a list of Column Names of DataFrame i.e.

or

Now modify the list,

This modification will not be reflected in original DataFrame object and DataFrame object will remain same i.e.

Accessing & Modifying Row Indexes in DataFrame

Contents of dataframe objects () is as follows,

Let’s access and modify its row indexes,

Get List of all Row Indexes from DataFrame

To get the list of all row index names from a dataFrame object, use index attribute instead of columns i.e. df.index.values

It returns an ndarray of all row indexes in dataframe i.e.

Get Row Index name by position in DataFrame

As df.index.values is a ndarray, so we can access it contents by position too. So, let’s get the name of column at position 2 i.e.

Changing the name of a Row Index in DataFrame

Any modification in this ndArray (df.index.values) will modify the actual DataFrame. For example let’s change the name of row index at position 0 i.e.

This change will be reflected in linked DataFrame object too. Now contents of DataFrame object is,

But if we convert it to list before modifying then changes will not be reflected in original DataFrame object. For example create a copy list of Row Index Names of DataFrame i.e.

Complete example is as follows :

Output:

 

 

Click Here to Subscribe for more Articles / Tutorials like this.