python - 使用 delim_whitespace、read_csv 指定最大分隔符

标签 python pandas

我在名为 results 的变量中得到以下结果:

data = """
0 a b this is my first file
1 c d this is my second file
2 e f this is my third file
3 g h this is my fourth file
4 i j this is my fifth file
"""

我想将结果解析为 pandas DataFrame。 我想要的结果是

调用read_csv
<表类=“s-表”> <标题> <正文> 0 一个 b 这是我的第一个文件 1 c d 这是我的第二个文件 2 e f 这是我的第三个文件

相反,当我打电话时:

read_csv(StringIO(results), delim_whitespace=True),我得到:

<表类=“s-表”> <标题> <正文> 0 一个 b 这个 是 我的 首先 文件 1 c d 这个 是 我的 第二次 文件 2 e f 这个 是 我的 第三个 文件

有没有办法在使用 delim_whitespace 时指定最大分隔符数量

最佳答案

# Data
results = """a b this is my first file
c d this is my second file
e f this is my third file
g h this is my fourth file
i j this is my fifth file"""

lines = results.split("\n")
words = [line.split(maxsplit=2) for line in lines]
df = pd.DataFrame(words)

关于python - 使用 delim_whitespace、read_csv 指定最大分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69619031/

相关文章:

python - 按每组中小于最大值 80% 的值对 pandas 数据框进行子集化。如何?

Python 等价于 Ruby Array.each 方法

python - 使用 tox 安装可选的依赖项

python - 如何解析 Suds 客户端请求的输出

python - 如何根据 Python Pandas 中 DataFrame 中其他 2 列中的值删除一列中的重复项?

python - 如何在单独的数据帧之间合并和分组

Python Selenium WebDriver 在新版本(2.4.9)中无法执行 quit()

python - 在 django 模板中呈现 HTML(不是 unicode 而是 ASCII)

python - 如何旋转 pandas DataFrame 列以创建二进制 "value table"?

python - Seaborn 中条形图和误差线的美观