我认为在使用panda从文本文件读取数据时,使用行终止符有问题。它在NaN列的末尾提供了一个不需要的行。我的数据有12行加一个头,但使用提供的代码,它会产生13行加一个头。我怎样才能让它输出正确的数据。
使用 将数据写入文本文件
with open(filepath, 'a', newline='') as filey:
csv_writer = csv.writer(filey, delimiter = 't', lineterminator='rn')
代码
import pandas as pd
path_to_results = r"C:\...\Desktop\Results\_results.txt"
data = pd.read_csv(path_to_results,sep='t',lineterminator='r')
data = pd.DataFrame(data)
#print(data.head())
print(data["Vi_V"])
print(data["mass_g"])
使用行终止符\r:
Name: Vi_V, dtype: object
0 0.24
1 0.47
...
11 3.66
12 NaN
使用行终止符\r\n:
追踪(最近一次通话(:
File "c:/Users.../g_00.py", line 5, in <module>
data = pd.read_csv(path_to_results,sep='t',lineterminator='rn')
File "C:...AppDataLocalProgramsPythonPython37libsite-packagespandasioparsers.py", line 676, in parser_f
return _read(filepath_or_buffer, kwds)
File "C:...AppDataLocalProgramsPythonPython37libsite-packagespandasioparsers.py", line 448, in _read
parser = TextFileReader(fp_or_buf, **kwds)
File "C:...AppDataLocalProgramsPythonPython37libsite-packagespandasioparsers.py", line 880, in __init__
self._make_engine(self.engine)
File "C:...AppDataLocalProgramsPythonPython37libsite-packagespandasioparsers.py", line 1114, in _make_engine
self._engine = CParserWrapper(self.f, **self.options)
File "C:...AppDataLocalProgramsPythonPython37libsite-packagespandasioparsers.py", line 1891, in __init__
self._reader = parsers.TextReader(src, **kwds)
File "pandas_libsparsers.pyx", line 395, in pandas._libs.parsers.TextReader.__cinit__
ValueError: Only length-1 line terminators supported
dee cue在评论中给出了答案:"你试过去掉行终止符参数吗?试着看看Windows上的python是否会自动将新行读取为\r\n-10月12日10:01";它奏效了。