How to Convert Row to Column and Column to Row of Dataframe in Python
To convert a row to a column and a column to a row in a dataframe in Python, you can use the melt() function and the transpose() function, respectively.
The following examples show how to convert rows to columns and columns to rows in Python.
Using melt() Function
We can use the melt() function to convert rows to columns.
Suppose we have the following dataframe:
# Import pandas library
import pandas as pd
# Define data
df = pd.DataFrame({'Price': [4500, 550, 250, 50, 350, 50], 'Status': [1, 1, 1, 0, 1, 1]})
# Convert rows to columns
converted_df = df.melt(var_name='Column', value_name='Value')
# Show dataframe
print(converted_df)
Output: 👇️
Column Value
0 Price 4500
1 Price 550
2 Price 250
3 Price 50
4 Price 350
5 Price 50
6 Status 1
7 Status 1
8 Status 1
9 Status 0
10 Status 1
11 Status 1
In this example, we use the melt() function to convert rows to columns in the dataframe df. The output shows the dataframe with rows converted to columns.
Using transpose() Function
We can use the transpose() function to convert columns to rows.
Suppose we have the following dataframe:
# Import pandas library
import pandas as pd
# Define data
df = pd.DataFrame({'Price': [4500, 550, 250, 50, 350, 50], 'Status': [1, 1, 1, 0, 1, 1]})
# Convert columns to rows
converted_df = df.T
# Show dataframe
print(converted_df)
Output: 👇️
0 1 2 3 4 5
Price 4500 550 250 50 350 50
Status 1 1 1 0 1 1
In this example, we use the transpose() function to convert columns to rows in the dataframe df. The output shows the dataframe with columns converted to rows.
Conclusion
We can use the melt() function to convert rows to columns and the transpose() function to convert columns to rows in a dataframe in Python. These methods provide a convenient way to reshape dataframes.