[Python] Using loops to extract data in Python from .csv files

Discussão em 'Python' iniciado por Stack, Outubro 2, 2024.

  1. Stack

    Stack Membro Participativo

    I am still very new to Python. I have extracted some data - tyre sales from a .csv file in 2023/24 (all numbers are made up). Here, the tyre sales have been summarised by month.

    import pandas as pd

    Tyre_sales_month = pd.read_csv('link/All_Sales_202324.csv')
    results_pivot = pd.pivot_table(
    Tyre_sales_month,
    values=['Tyre_Sales'],
    index=['Month'],
    aggfunc={'Tyre_Sales': 'sum'})
    cols = 'Tyre_Sales'
    results_pivot = results_pivot[cols]
    results_pivot.to_csv('link/Tyre_Sales_202324.csv')


    The output in the .csv file looks as follows:

    Month Tyre_Sales
    January $5,000
    February $7,000
    March $6,500
    April $5,500
    May $7,200
    June $8,500
    July $7,500
    August $5,200
    September $7,500
    October $8,500
    November $6,200
    December $7,500


    I now need to create a loop for the code to go through the following .csv files:

    All_Sales_202021.csv
    All_Sales_202122.csv
    All_Sales_202223.csv
    All_Sales_202324.csv


    and extract the Tyre_Sales information for previous years (from 202021 until 202324 inclusive) into the following outputs:

    Tyre_Sales_202021.csv
    Tyre_Sales_202122.csv
    Tyre_Sales_202223.csv
    Tyre_Sales_202324.csv


    I am still getting my head around loops in Python:

    # Years
    years = ['202021', '202122', '202223', '202324']
    years_data = {}

    year_data[year] = pd.read_csv("link/All_Sales_" + year + ".csv")


    Not sure how to link the year data with the code below and how to introduce a loop for the code to go through All_Sales files

    results_pivot = pd.pivot_table(
    Tyre_sales_month,
    values=['Tyre_Sales'],
    index=['Month'],
    aggfunc={'Tyre_Sales': 'sum'})
    cols = 'Tyre_Sales'
    results_pivot = results_pivot[cols]
    results_pivot.to_csv("link/Tyre_Sales_" + year + ".csv")


    Any guidance or help in this direction would be much appreciated.

    Continue reading...

Compartilhe esta Página