首页 > 解决方案 > Pandas:将一行字符串分成 4 列;问题:列由逗号、制表符和空格分隔

问题描述

我有一个文本文件,我正在尝试将一行的条目分隔到一个新列中。一行看起来像这样:

12:00,信息“这里有 18 个空格”ABC 一些文本<

我是这样开始的

table = pd.read_table(file, 
                  sep=',',
                  names=['Time', 'ID'])

现在我有一个包含 2 列的数据框:时间和 ID 但是我如何分隔“ID”列?特别是当条目由制表符和空格分隔时。

非常感谢!

标签: pythonpandas

解决方案


您可以使用正则表达式模式来精确定义拆分字符串行的规则:

import pandas as pd

df = pd.DataFrame(data={
    "A": [
        "12:00, Info    ABC some text\tmoretext"
    ]
})

# split on comma followed by a space OR 1+ whitespace (inc. tab) character 
df.A.str.split(r", |\s+", expand=True)

       0     1    2     3     4         5
0  12:00  Info  ABC  some  text  moretext


推荐阅读