从csv文件中切片/拆分某些字符

2024-09-28 21:03:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用熊猫库读取文件夹中的30个csv文件。以下是路径中“deg泷u pvsyst泷u runs”文件夹中的文件名 S:/Home/deg\ pvsyst\运行/

文件名为:

 "Energy_Base_Year00_-0.6%modqual.csv",
 "Energy_Base_Year01_-0.3%modqual.csv",  ......,  
 "Energy_Base_Year30_-8.4%modqual.csv

我想从上面的文件名中添加名为“年”“降级”的列表。你知道吗

“年”应为个位数0,1,2,…,30,“退化”应为-0.6,-0.3,0,…,8.1,来自文件“Energy\u Base\u Year00\u-0.6%modqual.csv文件“能源基础年01年-0.3%modqual.csv文件“能源基础年30%—8.4%modqual.csv文件分别是。你知道吗

我的代码如下:

     import os, csv, re
     import pandas as pd

     Year =[]
     Degradation = []

     cwd = os.getcwd()
     csv_files = [f for f in os.listdir(cwd + '\\' + 'deg_pvsyst_runs') if f.endswith('.csv')]

     for i,j in enumerate(csv_files):
         Year.append(csv_files[i].split("_Year")[1].split("_")[0])
         Degradation.append(csv_files[i].split("_")[1].split("modqual")[0])

最后,我想在csv中打印结果,名为“结果.csv“如下所示(只有2行30行显示):

enter image description here

[编辑]:

    I am getting output 

    Year as ['00','01'...'30'] and Base as ['Base'.'Base'...'Base']

    Whereas I want output as
    Year as ['0','1',...,'30'] and Base as ['-0.6','-0.3','0',...,'8.4']

Tags: 文件csv文件夹baseos文件名asruns
3条回答
  • 这里假设您需要年作为int,退化作为float。你知道吗
  • 如果您希望降级为str,只需删除float选项。你知道吗
  • 下面两行假设输入一致,如示例所示。你知道吗
Year.append(int(csv_files[i].split("_Year")[1].split("_")[0])) #if you want year as string you can map this to str again to get them as string.
Degradation.append(float(csv_files[i].split("_")[3].split("%modqual")[0]))

使用以下方法:

import os
import pandas as pd

years, degradations = [], []
cwd = os.getcwd()
csv_files = [f for f in os.listdir(os.path.join(cwd, 'deg_pvsyst_runs')) if f.endswith('.csv')]

for f in csv_files:
    *name_parts, deg = os.path.basename(f).split('_')
    years.append(int(name_parts[-1].replace('Year', '')))
    degradations.append(deg[:deg.index('%')])

pd.DataFrame({'Year': years, 'Degradation': degradations, 'Folder': csv_files})\
    .to_csv('result.csv', index=False)

你可以使用列表理解来实现这一点

Year = [k.split("_Year")[1].split("_")[0] for k in csv_files]
Year = [y[1] if y.startswith('0') else y for y in Year]
Degradation = [k.split("_")[-1].split(r"%modqual")[0] for k in csv_files]

相关问题 更多 >