在 Python 中使用循环从 .csv 文件中提取数据

问题描述 投票:0回答:1

我对 Python 还很陌生。我提取了一些数据 - 轮胎销售量来自
2023/24 年的 .csv 文件(所有数字均为虚构)。这里,轮胎销量已按月汇总。

将 pandas 导入为 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')

.csv 文件中的输出如下所示:

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.
python loops csv
1个回答
0
投票

你可以这样尝试

import pandas as pd

years = ['202021', '202122', '202223', '202324']

for year in years:
    # Construct paths
    input_file = "link/All_Sales_" + year + ".csv"
    output_file = "link/Tyre_Sales_" + year + ".csv"

    # Read CSV file year and process data
    tyre_sales_month = pd.read_csv(input_file)

results_pivot = pd.pivot_table(
    tyre_sales_month,
    values=['Tyre_Sales'],
    index=['Month'],
    aggfunc={'Tyre_Sales': 'sum'}
)

# Select 'Tyre_Sales' and save as CSV file
results_pivot = results_pivot['Tyre_Sales']
results_pivot.to_csv(output_file)

print(f"done for {year}")

你还可以在最后检查类似的错误:

except FileNotFoundError:
    print(f"{year} file not found, skip")
except Exception as exc:
    print(f"error {year}: {exc}")
© www.soinside.com 2019 - 2024. All rights reserved.