python - 如何查找特定值的列号以及该位置的 CSV 文件

标签 python pandas numpy

我正在尝试在特定行中使用特定值拆分 csv 文件,但我不知道该怎么做。 csv 文件是我们使用的程序导出的数据,它由两个不同的部分组成。该文件如下所示,第二部分始终以“[Faces]”开头。

[Name]
Plane 1750

[Data]
Node Number, X [ m ], Y [ m ], Z [ m ], AV WF
0, -1.96213058e+02, -2.73303375e+02, 1.75000000e+00, 2.01742917e-01
1, -1.96173523e+02, -2.73252655e+02, 1.75000000e+00, 2.02091664e-01
606479, -2.06638428e+02, 2.93843475e+02, 1.75000000e+00, 3.21377516e-01
606480, -2.05079956e+02, 2.94933014e+02, 1.75000000e+00, 3.27591240e-01

[Faces]
400, 335, 336, 339, 338
196775, 644, 610, 611, 196774
1658, 1657, 1656, 196787, 196788
1562, 1561, 1439, 1438, 196794

现在我想知道如何在值“[Faces]”的位置拆分文件并将其下方的所有数据保存在新的 csv 文件中。

此执行是已使用 pandas 和 numpy 的脚本的一部分。

最佳答案

尝试消耗线直到我们遇到[Faces]线:

with open('data.txt') as fp:
    while fp.readline().strip() != '[Faces]':
        pass
    df = pd.read_csv(fp, header=None, skipinitialspace=True)

with open('faces.csv') as fp:
    fp.write('[Faces]\n')
    df.to_csv(fp, index=False)

faces.csv 的内容:

[Faces]
0,1,2,3,4
400,335,336,339,338
196775,644,610,611,196774
1658,1657,1656,196787,196788
1562,1561,1439,1438,196794

更新

没有 Pandas :

with open('data.txt') as inp, open('faces.csv', 'w') as out:
    while inp.readline().strip() != '[Faces]':
        pass
    out.writelines(['Faces\n'] + inp.readlines())

更新2

import shutil

with open('data.txt', 'r') as inp, \
     open('faces.csv', 'w') as out, \
     open('temp.txt', 'w') as tmp:
    fp = tmp
    for line in inp:
        if line == '[Faces]\n':
            fp = out
        fp.write(line)

shutil.move('temp.txt', 'data2.txt')

关于python - 如何查找特定值的列号以及该位置的 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70521522/

相关文章:

python - Numpy Where 有两个以上的条件

Python 的reduce 函数混淆

python - 将 Pandas DataFrame 转换为分层列/更改列层次结构

python - 根据 pandas 第三列中的条件在两列中的值之间进行选择

python - 如何将标量添加到特定范围内的 numpy 数组?

Python ctypes 到位域的 np.dtype 转换

python - KivyMD 按钮 : How increase its dimensions

Python 3 Bokeh Heatmap 矩形简单示例未在图中显示任何内容

python - 获取满足条件的所有可能的 3x2 矩阵的数量

python - 如何处理 Pandas 中等于 "NA"的列?