SoFunction
Updated on 2025-03-03

Detailed explanation of how to use pandas to convert data rows and columns to rows

1. Data column to row

import pandas as pd  # Import pandas library
def pivot_excel_data(input_file, output_file):
    """
    Will Excel Convert data rows in the file into columns,and save as new Excel document
    
    Parameters:
        input_file (str): Input Excel document路径
        output_file (str): Output Excel document路径
        
    Returns:
        None
    """
    # Read Excel data    df = pd.read_excel(input_file, sheet_name='Sheet1')
    
    # Use the pivot_table() function to convert data rows into columns    df_pivot = df.pivot_table(index='Shop', columns='New Fee Type', values='Amount').reset_index()
    
    # Save the processed data to a new Excel file    df_pivot.to_excel(output_file, index=False)

# Call function for data processinginput_file = 'C:\\Users\\Administrator\\Desktop\\New Data_After Processing.xlsx'
output_file = 'converted_data.xlsx'
pivot_excel_data(input_file, output_file)

2. Data rows and columns

import pandas as pd  # Import pandas library
def melt_excel_data(input_file, output_file):
    """
    Will Excel Convert data columns in the file to rows,and save as new Excel document
    
    Parameters:
        input_file (str): Input Excel document路径
        output_file (str): Output Excel document路径
        
    Returns:
        None
    """
    # Read Excel data    df = pd.read_excel(input_file, sheet_name='Sheet1')
    
    # Use melt() function to convert data columns into rows    df_melted = (id_vars=['Shop'], var_name='Fee Type', value_name='Amount')
    
    # Save the processed data to a new Excel file    df_melted.to_excel(output_file, index=False)

# Call function for data processinginput_file = 'C:\\Users\\Administrator\\Desktop\\converted_data.xlsx'
output_file = 'converted_data2.xlsx'
melt_excel_data(input_file, output_file)

This is the article about how to use pandas to transfer data rows and columns to transfer columns. For more related pandas rows and columns, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!