首页 > 解决方案 > 如何将多个文件提供给 pandas 以过滤数据并连接所有结果

问题描述

我编写了一个代码来执行一些数据清理,以从制表符间隔的文件中获取最终的列和值。

import matplotlib.image as image
import numpy as np
import tkinter as tk
import matplotlib.ticker as ticker
from tkinter import filedialog
import matplotlib.pyplot as plt
root = tk.Tk()
root.withdraw()
root.call('wm', 'attributes', '.', '-topmost', True)
files1 = filedialog.askopenfilename(multiple=True) 
files = root.tk.splitlist(files1)

List = list(files) 

%gui tk
for i,file in enumerate(List,1):
    d = pd.read_csv(file,sep=None,engine='python')
    h = d.drop(d.index[19:])
    transpose = h.T
    header =transpose.iloc[0]
    df = transpose[1:]
    df.columns =header
    df.columns = df.columns.str.strip()
    all_columns = list(df)
    df[all_columns] = df[all_columns].astype(str)
    k =df.drop(columns =['Op:','Comment:','Mod Type:', 'PN', 'Irradiance:','Irr Correct:', 'Lamp Voltage:','Corrected To:', 'MCCC:', 'Rseries:', 'Rshunt:'], axis=1)     
k.head()

我想将此代码运行到多个文件并执行相同操作并将所有结果连接到一个数据帧。

例如,如果我选择 20 个文件,则新的数据框带有一行标题和下面的所有 20 个结果,列 ['Module Temp:'] 中的值按递增顺序排列。

如果有人可以为这个问题提供解决方案,那就太好了

请找到示例数据的链接:https ://drive.google.com/drive/folders/1sL2-CwCGeGm0-fvcpzMVzgFnYzN3wzVb?usp=sharing

标签: pythonpandascsvconcatenation

解决方案


  • 以下代码显示了如何解析文件并提取数据。它不显示tkinterGUI 组件。files将代表您选择的文件。
  • 假设:
    • 文件的前 92 行始终是测量参数
    • 第 93 行是测量值。
    • 每个'Module Temp'文件的不同
  • 列表将根据 的排序顺序进行排序mod_temp,因此数据将在 DataFrame 中按顺序排列。
import pandas as p
from patlib import Path

# set path to files
path_ = Path('e:/PythonProjects/stack_overflow/data/so_data/2020-11-16')

# select the correct files
files = path_.glob('*.ivc')

# create lists for metrics
measurement_params = list()
mod_temp = list()
measurements = list()

# iterate through the files
for f in files:
    
    # get the first 92 rows with the measurement parameters
    mp = pd.read_csv(f, sep='\t', nrows=91, index_col=0)
    
    # remove the whitespace and : from the end of the index names
    mp.index = mp.index.str.replace(':', '').str.strip().str.replace('\\s+', '_')
    
    # get the column header
    col = mp.columns[0]
    
    # get the module temp
    mt = mp.loc['Module_Temp', col]
    
    # add Modult_Temp to mod_temp
    mod_temp.append(float(mt))
    
    # get the measurements
    m = pd.read_csv(f, sep='\t', skiprows=92, nrows=3512)
    
    # remove the whitespace and : from the end of the column names
    m.columns = m.columns.str.replace(':', '').str.strip()

    # add Module_Temp column
    m['mod_temp'] = mt
    
    # store the measure parameters
    measurement_params.append(mp.T)
    
    # store the measurements
    measurements.append(m)
    
# sort lists based on mod_temp sort order
measurement_params = [x for _, x in sorted(zip(mod_temp, measurement_params))]
measurements = [x for _, x in sorted(zip(mod_temp, measurements))]

# create a dataframe for the measurement parameters
df_mp = pd.concat(measurement_params)

# create a dataframe for the measurements
df_m = pd.concat(measurements).reset_index(drop=True)

df_mp

Title:             Comment     Op               ID     Mod_Type   PN        Date      Time Irradiance IrrCorr Irr_Correct Lamp_Voltage Module_Temp Corrected_To    MCCC      Voc      Isc  Rseries   Rshunt     Pmax      Vpm      Ipm Fill_Factor Active_Eff Aperture_Eff Segment_Area Segs_in_Ser Segs_in_Par Panel_Area Vload Ivld Pvld Frequency SweepDelay SweepLength SweepSlope SweepDir MCCC2  MCCC3  MCCC4    LampI     IntV   IntV2 IntV3 IntV4 LoadV PulseWidth1 PulseWidth2 PulseWidth3 PulseWidth4    TRef1 TRef2 TRef3 TRef4 MCMode Irradiance2 IrrCorr2 Voc2 Isc2 Pmax2 Vpm2 Ipm2 Fill_Factor2 Active_Eff2 ApertureEff2 LoadV2 PulseWidth12 PulseWidth22 Irradiance3 IrrCorr3 Voc3 Isc3 Pmax3 Vpm3 Ipm3 Fill_Factor3 Active_Eff3 ApertureEff3 LoadV3 PulseWidth13 PulseWidth23                RefCellID RefCellTemp RefCellIrrMM RefCelIscRaw RefCellIsc VTempCoeff ITempCoeff PTempCoeff MismatchCorr  Serial_No Soft_Ver
Nease 345W N345M72     STC  Admin    MCIND2021-058  ModuleType1  NaN  10-09-2020  19:12:52    100.007     100    Ref Cell         2400     25.2787           25  1.3669  46.4379  9.13215  0.43411  294.467  331.924  38.3403  8.65732     0.78269    1.89434       1.7106       243.36          72           1      19404     0    0    0    218000         10         100      0.025        0     1  1.155  1.155  20.4736  6.87023  6.8645     6     6  6.76     107.683     109.977           0           0  27.2224     0     0     0  False     -1.#INF       70    0    0     0    0    0            0           0            0      5      107.683      109.977     -1.#INF       40    0    0     0    0    0            0           0            0      5      107.683      109.977  WPVS mono C-Si Ref Cell     25.9834      1001.86      0.15142    0.15135      -0.31       0.05       -0.4       0.9985  S91-00052    5.5.1
Solarium SGE24P330     STC  Admin  MCIND_2021_0074  ModuleType1  NaN  17-09-2020  15:06:12    99.3671     100    Ref Cell         2400     25.3380           25  1.3669  45.2903  8.87987  0.48667  216.763  311.031  36.9665  8.41388     0.77338    1.77510      1.60292       243.36          72           1      19404     0    0    0    218000         10         100      0.025        0     1  1.155  1.155   20.405  6.82362  6.8212     6     6   6.6     107.660     109.977           0           0  25.9418     0     0     0  False     -1.#INF       70    0    0     0    0    0            0           0            0  4.943      107.660      109.977     -1.#INF       40    0    0     0    0    0            0           0            0  4.943      107.660      109.977  WPVS mono C-Si Ref Cell     25.3315      998.370      0.15085    0.15082      -0.31       0.05       -0.4       0.9985  S91-00052    5.5.1
Nease 345W N345M72     STC  Admin    MCIND2021-058  ModuleType1  NaN  10-09-2020  19:11:32    100.010     100    Ref Cell         2400     25.3557           25  1.3669  46.4381  9.11368  0.41608  299.758  331.418  38.3876  8.63345     0.78308    1.89144      1.70798       243.36          72           1      19404     0    0    0    218000         10         100      0.025        0     1  1.155  1.155  20.3820  6.87018  6.8645     6     6  6.76     107.683     109.977           0           0  27.2535     0     0     0  False     -1.#INF       70    0    0     0    0    0            0           0            0      5      107.683      109.977     -1.#INF       40    0    0     0    0    0            0           0            0      5      107.683      109.977  WPVS mono C-Si Ref Cell     25.9614      1003.80      0.15171    0.15164      -0.31       0.05       -0.4       0.9985  S91-00052    5.5.1
Nease 345W N345M72     STC  Admin    MCIND2021-058  ModuleType1  NaN  10-09-2020  19:14:09    99.9925     100    Ref Cell         2400     25.4279           25  1.3669  46.4445  9.14115  0.43428  291.524  332.156  38.2767  8.67776     0.78236    1.89566      1.71179       243.36          72           1      19404     0    0    0    218000         10         100      0.025        0     1  1.155  1.155  20.5044  6.87042  6.8645     6     6  6.76     107.660     109.977           0           0  27.1989     0     0     0  False     -1.#INF       70    0    0     0    0    0            0           0            0      5      107.660      109.977     -1.#INF       40    0    0     0    0    0            0           0            0      5      107.660      109.977  WPVS mono C-Si Ref Cell     26.0274      1000.93      0.15128    0.15121      -0.31       0.05       -0.4       0.9985  S91-00052    5.5.1

df_m.head()

    Voltage   Current mod_temp
0 -1.193405  9.202885  25.2787
1 -1.196560  9.202489  25.2787
2 -1.193403  9.201693  25.2787
3 -1.196558  9.201298  25.2787
4 -1.199711  9.200106  25.2787

df_m.tail()

        Voltage   Current mod_temp
14043  46.30869  0.315269  25.4279
14044  46.31411  0.302567  25.4279
14045  46.31949  0.289468  25.4279
14046  46.32181  0.277163  25.4279
14047  46.33039  0.265255  25.4279

阴谋

import seaborn as sns
import matplotlib.pyplot as plt

plt.figure(figsize=(20, 8))
sns.scatterplot(x='Current', y='Voltage', data=df_m, hue='mod_temp', s=10)
plt.show()

在此处输入图像描述

笔记

  • 这样做之后,我在绘制数据时遇到了麻烦,因为列不是浮点类型。但是,尝试设置类型时发生错误。回头看数据,在第 92 行之后,两列有多个表头。
    • 第 93 行:电压:电流:
    • 第 3631 行:参考单元:灯 I:
    • 第 7169 行:电压 2:电流 2:
    • 第 11971 行:参考单元 2:灯 I2:
    • 第 16773 行:电压 3:电流 3:
    • 第 21575 行:参考单元 3:灯 I3:
    • 第 26377 行:原始电压:原始电流:
    • 第 29915 行:WPVS 电压:WPVS 电流:
  • 我在创建时返回并使用了该nrows参数m,因此仅从文件中提取了第一组标题和相关的测量值。
  • 我建议使用模块编写脚本csv来读取每个文件,并从每个空白行开始创建一个新文件,这将使文件具有一致的测量类型。
    • 如果需要,这应该是一个新问题。

推荐阅读