我有包含 5000 行的 CSV,每隔几百行 CSV 就有一个重复部分。
将此文件分成几个不同的文件的最有效选择是什么?
文件看起来像
Header1
number of Samples1
Content1
a1, aa1, aaa1
b1, bb1, bbb1
....
Header2
number of Samples2
Content2
a2, aa2, aaa2
b2, bb2, bbb2
....
Header3
number of Samples3
Content3
a3, aa3, aaa3
b3, bb3, bbb3
我需要通过Header 把它分成几个文件。我不知道我该怎么做。我编写了整个脚本来处理一些生物 Material ,但是其中一种文件类型(上面)会产生问题,因为它是一个文件中的多个文件。并且脚本不想使用它。
我已经阅读了很多关于拆分文件的内容,但是我没有发现任何关于在 pandas 中重复值后的分离。
在这种情况下,它将是 3 个文件(但文件中这些文件的数量会有所不同)
请您参考如下方法:
我发现了比 break 语句更好的解决方案,正如我在评论中所建议的那样:
您可以创建 result 列表并将每个 block 数据存储在列表的单独元素中(例如,在字典中)。如果您阅读非Header 行,您可以保证您刚刚阅读的行与当前数据 block 相关。而当前数据 block 是 result 列表中的最后一个元素,所以你可以修改它。如果您阅读 Header 行,您只需将新元素附加到 result 并开始将新 block 数据写入其中。
如果内容的大小不变,您可以使用 itertools.cycle 迭代器来“编码”您的解析过程:
from itertools import cycle
text1 = """Header1
number of Samples1
Content1
a1, aa1, aaa1
b1, bb1, bbb1
Header2
number of Samples2
Content2
a2, aa2, aaa2
b2, bb2, bbb2"""
size = 5
iterator = cycle(range(size))
result = []
for line in text1.split('\n'):
i = next(iterator)
if i == 0:
result.append({'header': line})
elif i == 1:
result[-1]['num_of_samples'] = line
elif i == 2:
result[-1]['content_header'] = line
elif i == 3:
result[-1]['content'] = [line.split(', ')]
else:
result[-1]['content'].append(line.split(', '))
如果您不知道内容的大小,您应该解析每一行,检查其类型并手动构建数据:
text2 = """Header1
number of Samples1
Content1
a1, aa1, aaa1
b1, bb1, bbb1
b1, bb1, bbb1
Header2
number of Samples2
Content2
b2, bb2, bbb2
Header3
number of Samples3
Content3
a3, aa3, aaa3
b3, bb3, bbb3"""
result = []
i = 0
for line in text2.split('\n'):
if line.startswith('Header'): # Your condition for headers
result.append({'header': line})
elif line.startswith('number'): # Your condition for number of samples
result[-1]['num_of_samples'] = line
elif line.startswith('Content'): # Your condition for content headers
result[-1]['content_header'] = line
else:
if 'content' not in result[-1]: # We don't know is the content list created
result[-1]['content'] = [line.split(', ')]
else:
result[-1]['content'].append(line.split(', '))
