如何从csv-fi获取新文件中的写自定义表

2024-04-23 23:21:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个脚本,从csv文件中提取表,并编写一个包含此表的新csv文件。 所以我有下面的代码:

import csv
import pandas as pd

with open("C:\\OpenFace\\x64\\Release\\processed\\webcam_2019-04-22-1552.csv") as csvfile:
    ddf= pd.read_table(csvfile,sep=" ")
    first_letters = ['eye']
    headers = ddf.dtypes.index
    df= pd.read_table(csvfile,sep=" ",names=[name for name in headers if (name[0] in first_letters)])
    print(df)

我只想得到从眼睛开始的列名, 但我有个错误:

Traceback (most recent call last):
File "getpoints.py", line 8, in <module>
df= pd.read_table(csvfile,sep=" ",names=[name for name in headers if 
(name[0] in first_letters)])
File "C:\Python36\lib\site-packages\pandas\io\parsers.py", line 678, in parser_f
return _read(filepath_or_buffer, kwds)
File "C:\Python36\lib\site-packages\pandas\io\parsers.py", line 440, in _read
parser = TextFileReader(filepath_or_buffer, **kwds)
File "C:\Python36\lib\site-packages\pandas\io\parsers.py", line 787, in __init__
self._make_engine(self.engine)
File "C:\Python36\lib\site-packages\pandas\io\parsers.py", line 1014, in _make_engine
self._engine = CParserWrapper(self.f, **self.options)
File "C:\Python36\lib\site-packages\pandas\io\parsers.py", line 1708, in __init__
self._reader = parsers.TextReader(src, **kwds)
File "pandas\_libs\parsers.pyx", line 542, in pandas._libs.parsers.TextReader.__cinit__
pandas.errors.EmptyDataError: No columns to parse from file

如何解决这个问题? 有什么想法吗

谢谢


Tags: csvnameinpyioselfpandasread
1条回答
网友
1楼 · 发布于 2024-04-23 23:21:35


import csv
import pandas as pd

#Read the only the header, i.e column names and breaks the execution 
#as only the column names is to be fetched.

with open("C:/path/to/.csv", "rb") as f:
    reader = csv.reader(f)
    columns = reader.next()
    break


columns = list(filter(lambda x: x.startswith("eye"), columns))

df = pd.read_csv("C:/path/to/.csv", sep=" ", names=columns)

相关问题 更多 >