【问题标题】:How to get write custom tables in new file from csv file如何从 csv 文件在新文件中写入自定义表
【发布时间】:2019-09-12 11:47:55
【问题描述】:

我编写了一个脚本来从 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)

我试图只获取从 eye 开始的列名, 但我收到此错误:

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

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

谢谢。

【问题讨论】:

    标签: python pandas file csv


    【解决方案1】:
    
    
    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)
    

    【讨论】:

    • C:\OpenFace>python getpoints.py 文件“getpoints.py”,第 10 行 break ^ SyntaxError: 'break' outside loop C:\OpenFace>python getpoints.py Traceback(最近一次调用最后):文件“getpoints.py”,第 9 行,在 列 = reader.next() AttributeError: '_csv.reader' object has no attribute 'next'
    • 当我更正这些错误时,我没有得到我想要的格式。 i.imgur.com/ChnXupq.png
    猜你喜欢
    • 1970-01-01
    • 2021-07-17
    • 2019-10-03
    • 2014-05-10
    • 2019-07-23
    • 2018-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多