Pandas忽略作为参数传递的分隔符

问题描述 投票:-1回答:2

我正在研究一个函数,除其他任务之外,应该在pandas中读取csv。作为参数之一,我想将分隔符作为字符串传递。但是,出于某种原因,可能与正则表达式有关,pandas完全忽略了我传递的解析器并默认为'\ t',它不能正确解析我的数据。

import pandas as pd

def open_df(separator):
  df = pd.read_csv('filename.csv', sep=separator)
  return df

问题是,在这种情况下我怎么想传递分隔符参数?

python pandas csv separator
2个回答
3
投票

请检查此链接:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html

sep:str,默认','

Delimiter to use. If sep is None, the C engine cannot automatically detect the separator, but the Python parsing engine can,

意味着后者将被使用并通过Python的内置嗅探器工具csv.Sniffer自动检测分隔符。此外,长度超过1个字符且与'\ s +'不同的分隔符将被解释为正则表达式,并且还将强制使用Python解析引擎。请注意,正则表达式分隔符很容易忽略引用的数据。正则表达式示例:'\ r \ t'。


1
投票

我将分隔符字符串作为“原始”字符串传递,这对我来说很好。我使用原始字符串\被解释为普通字符,并且\ t也可以工作

当你调用open_df()时,你必须在open_df(r"\t")之类的字符串引号之前写一个r

例:

test_string = r"\t\n"
print(test_string)
\t\n

我还传递“python”作为引擎参数,以便不显示解析器警告:-)。

© www.soinside.com 2019 - 2024. All rights reserved.