我有一堆来自 HPLC 的 CSV 文件,当通过 pandas.read_csv 进行标准导入时,我得到类似这样的东西。
import pandas as pd
import glob
#get files from folder, careful, case sensitive
files = glob.glob('./*.txt')
df = pd.read_csv(files[0])
0 Application Name\tLabSolutions
1 Version\t5.93
2 Data File Name\tC:\LabSolutions\Data\outreach\...
3 Output Date\t11/12/2023
4 Output Time\t3:03:23 PM
但是当尝试将分隔符更改为制表符时
df = pd.read_csv(files[0], sep='\t')
我明白了
---------------------------------------------------------------------------
ParserError Traceback (most recent call last)
<ipython-input-627-dc81386f301e> in <cell line: 8>()
6
7 files = glob.glob('./*.txt')
----> 8 df = pd.read_csv(files[0], sep='\t')
9 df
9 frames
/usr/local/lib/python3.10/dist-packages/pandas/_libs/parsers.pyx in pandas._libs.parsers.raise_parser_error()
ParserError: Error tokenizing data. C error: Expected 2 fields in line 73, saw
可能出了什么问题?
这些文件的结构有点奇怪,其中定义的部分是这样的。
[File Information]
Type Data File
Generated 11/12/2023 9:51:47 AM
Generated by Lab2
Modified 11/12/2023 2:58:18 PM
Modified by Lab2
和
[Configuration]
Instrument Name S24564-Instrument1
Instrument # 1
Line # 1
# of Detectors 2
Detector ID Detector A Detector B
Detector Name Detector A Detector
# of Channels 2 1
有几个像这样的不同 block ,具有不同的数据行和列。
另一种选择是以某种方式获取每个文件的每个[部分],但我更不知道如何实现这一点。
我忘记了我尝试过的内容,而且我不知道这会如何导致错误,我所做的只是要求使用制表符而不是逗号作为分隔符。
最佳答案
根据错误,文件的第 73 行只有一个字段,因此不存在 \t
。
为了获得更多详细信息,我将使用 on_bad_lines
参数,如下所示:
import pandas as pd
import glob
#get files from folder, careful, case sensitive
files = glob.glob('./*.txt')
df = pd.read_csv(files[0], on_bad_lines='warn')
您应该能够拥有一个数据框,并在日志中包含带有警告的行(但我猜错误将与以前相同)。
on_bad_lines
参数的文档:
on_bad_lines{‘error’, ‘warn’, ‘skip’} or Callable, default ‘error’
Specifies what to do upon encountering a bad line (a line with too many fields). Allowed values are :
- 'error', raise an Exception when a bad line is encountered.
- 'warn', raise a warning when a bad line is encountered and skip that line.
- 'skip', skip bad lines without raising or warning when they are encountered.
关于python - 使用 sep ='\t' 在 Pandas 中读取 CSV 文件无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77470035/