【问题标题】:Remove entire row from CSV (if blank)从 CSV 中删除整行(如果为空)
【发布时间】:2016-06-23 18:12:15
【问题描述】:

我有一个来自仪器的数据文件,它以 CSV 格式输出。读取文件和相应的列没有问题,但是,由于检测的轻微变化,数据文件已经改变,我不确定如何更改我的代码以仍然读取文件。

f = open('Rotator_050816.dat')
lines = f.readlines()
i = 0
while (lines[i]<>"[Data]\n"):
   i+=1
i = i + 2
Temp = []; Field = []; Resistance1 = []; Resistance2 = [];
while(i<len(lines)):
    data = lines[i].split(",")
    Temp.append(float(data[3])
    Field.append(float(data[4])
    Resistance1.append(float[12])
    Resistance2.append(float[13])
i+=1

Temp = np.array(Temp)
Field_T = np.array(Field)/10000.
Resistance1 = np.array(Resistance1)
Excitation1 = np.array(Excitation1)

这是以前使用的 MWE。如果 CSV 文件没有空白条目,这没有问题,但是,如果有空白条目,则会出现问题,因为 len(Resistance1) ≠ len(Temp),因此无法正确绘制它们。所以我的数据文件现在看起来像这样:

Example Data File

所以我需要为 Res 添加可以读取一行的代码行。 Ch1 或水库。 Ch2 为空,然后在附加到最终数据集之前跳过所有变量的整行。这样 len(Resistance1) = len(Temp) 和每个 Res. Ch1 测量值与正确的温度相匹配。

【问题讨论】:

  • 这需要minimal reproducible example (MWE)。 [data] 是什么?此外,&lt;&gt; 不是有效的 Python 语法。另外,while 循环永远不会终止。
  • @MorganThrapp &lt;&gt; 是有效的 Python 2。
  • @StefanPochmann 嗯,我的立场是正确的。我不知道。
  • 为 MWE 添加了更多内容。它完全适用于没有空格的数据文件。
  • 看来你应该使用csv 模块。

标签: python csv matplotlib scientific-computing


【解决方案1】:

1) 以只读模式打开文件并获取所有行

lines_in_my_file = []
with open("my_file.csv", "r") as my_file:
    lines_in_my_file = my_file.readlines()

2) 再次打开文件,这次是写入模式,将所有非空行写入文件:

with open("my_file.csv", "r") as my_file:
    for line in lines_in_my_file:
        if line.strip().strip(",") != ""
            my_file.write(line)

请注意,这将删除任何仅由空格、制表符或逗号组成的行。所以任何看起来像这样的行:

,,,, (this line has only commas)
     (this line has only spaces)
\n   (this line is just a newline character)

...将被删除。

【讨论】:

    【解决方案2】:

    这是我已经实施的工作解决方案:

    while (i<len(lines)):
    data = lines[i].split(",")
        if float(data[4]) >30000 and float(data[4]) <50000:
            Temp_II.append(float(data[3]))  #As K
            Field_II.append(float(data[4]))   #As Oe
            Position_II.append(float(data[5])) #As Degree
            #loop for Resistivity1 column cleanup
            if data[12]!= '':
                Resistivity1_II.append(float(data[12]))
                Temp1_II.append(float(data[3]))
            #loop for Resistivity2 column cleanup
            if data[13]!= '':
               Resistivity2_II.append(float(data[13]))
               Temp2_II.append(float(data[3]))                        
    i+=1
    

    基本上,这会将非空白的 Resistivity1 条目与相应的 Temperature 条目配对,Resistivity2 也是如此。

    【讨论】:

      猜你喜欢
      • 2019-07-05
      • 2011-05-30
      • 1970-01-01
      • 2015-10-13
      • 1970-01-01
      • 1970-01-01
      • 2014-07-27
      • 2014-02-25
      • 2013-03-12
      相关资源
      最近更新 更多