Pandas Set_Index().T - Convert a Column Value into a Row

blog details
author


Using Pandas to manipulate the data is a set of fundamental skills used in so many applications. This article shares how to convert a column into a row Set_index().T given by Pandas. By the end of this piece, you can learn skills applied to data visualization, application development and some sections of machine learning


Ingredient to use Set_index().T to convert a column value into a row using Pandas

Python3, Pandas

Table of Contents


When we need to convert a column value into a row

Often the data response format and its visualization does not fit your expectation. Your purpose might be for updating the dashboard or developing application data interaction, so on and so forth. Take stock financial ratio analysis for example, here is a sample as follows:

In a way, the year time dataset sitting in the 1st column is not the best visualisation way to present the trend and data change over the time. On the other hand, if the year time dataset is converted into the header as follows, the look and feel is better, friendly and fits in the habit of audience reading.

Additionally, if the Python script is connected with a Google Sheet or an excel-format data hub, it can facilitate you to automate creating the line graph meanwhile by ranging the data from left side to the right ride of the data table.

Set_index()

This Panda method is to set the DataFrame index using existing columns.

Set the DataFrame index (row labels) using one or more existing columns or arrays (of the correct length). The index can replace the existing index or expand on it.

DataFrame.set_index(keys, *, drop=True, append=False, inplace=False, verify_integrity=False)

Take financial ratio data mentioned earlier for example. We like to use the year time data column as the index column. Here is the code as follows:

Df = pd.Dataframe(yourdatasource).set_index(‘Year)

Transpose() – .T

This method is to transpose indexes and columns. It reflects the DataFrame over its main diagonal by writing rows as columns and vice-versa. The property T is an accessor to the method transpose().

copy : bool, default False

If True, the underlying data is copied. Otherwise (default), no copy is made if possible.

*args, **kwargs

Additional keywords have no effect but might be accepted for compatibility with numpy.

For the case mentioned above after having set the new index, now necessarily we change the index as the header. Here is the code sample as follows:

Df2 = Df.T

Full Python Script Using Set_index.T of Easy2Digital Stock Company Financial Ratio Data API Sample


Share This Post

No Comment at the moment...