首页 > 解决方案 > Pandas 忽略作为参数传递的分隔符

问题描述

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

import pandas as pd

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

问题是,在这种情况下我应该如何传递分隔符参数?

标签: pythonpandascsvseparator

解决方案


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

sep : str, 默认 ','</p>

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'。


推荐阅读