【问题标题】:Space delimiter in CSV import to PythonCSV 导入 Python 中的空格分隔符
【发布时间】:2018-07-27 01:10:56
【问题描述】:

我知道关于 CSV 文件中的空格分隔符有很多问题。

我有一个似乎用空格分隔的 CSV 文件。在导入 Python 时,我尝试了所有代码来将空格标识为分隔符。但是,我不断收到错误消息。例如:

    test_filepath = 'test_data.csv'

with codecs.open(test_filepath, "r", "Shift-JIS", "ignore") as file:  # import UTF8 based csv file 
    test_df = pd.read_table( file, delim_whitespace=True )

这会产生以下错误:

EmptyDataError: No columns to parse from file

当我尝试这个时:

    test_filepath = 'test_data.csv'

with codecs.open(test_filepath, "r", "Shift-JIS", "ignore") as file:  # import UTF8 based csv file 
    test_df = pd.read_table( file, delimiter=" " )

它给出了同样的错误。

当我尝试这个时:

    test_filepath = 'test_data.csv'

with codecs.open(test_filepath, "r", "Shift-JIS", "ignore") as file:  # import UTF8 based csv file 
    test_df = pd.read_table( file, sep = "/s+" )

我得到同样的错误。

当我尝试这个时:

        test_filepath = 'test_data.csv'

with codecs.open(test_filepath, "r", "Shift-JIS", "ignore") as file:  # import UTF8 based csv file 
    test_df = pd.read_table( file, delimiter='\t')

我得到同样的错误。

我没有得到错误的唯一方法是如果我这样做:

        test_filepath = 'test_data.csv'

with codecs.open(test_filepath, "r", "Shift-JIS", "ignore") as file:  # import UTF8 based csv file 
    test_df = pd.read_table( file, delimiter=',')

但结果看起来完全不正确,并且 test_df.info() 显示只创建了一列(应该有 100 列)。

【问题讨论】:

  • 有标题吗?
  • 你怎么知道你的数据是用空格分隔的?你打开你的数据并查看了吗?您的回溯似乎认为您没有任何数据。
  • 在excel中打开并用空格分隔
  • 与其疯狂地猜测你有什么样的空白,为什么不实际读取其中一行(只是row = file.readline())然后print repr(row),实际上看看什么你有吗?
  • 另外,您需要更仔细地阅读文档。 /s+ 没有任何意义——或者,更确切地说,它意味着您想用文字斜线和一个或多个字母 ss 分隔列,这不是很有用。

标签: python pandas csv delimiter separator


【解决方案1】:

我认为 pandas 可以解决问题,其中一个应该可以。

import pandas as pd

df = pd.read_csv('file.csv', delim_whitespace=True)  
df = pd.read_csv('file.csv', delimiter=' ')

【讨论】:

    猜你喜欢
    • 2015-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-26
    • 1970-01-01
    • 2018-10-25
    • 1970-01-01
    相关资源
    最近更新 更多