python - Pandas:将一行字符串分成 4 列;问题:列由逗号、制表符和空格分隔
问题描述
我有一个文本文件,我正在尝试将一行的条目分隔到一个新列中。一行看起来像这样:
12:00,信息“这里有 18 个空格”ABC 一些文本<
我是这样开始的
table = pd.read_table(file,
sep=',',
names=['Time', 'ID'])
现在我有一个包含 2 列的数据框:时间和 ID 但是我如何分隔“ID”列?特别是当条目由制表符和空格分隔时。
非常感谢!
解决方案
您可以使用正则表达式模式来精确定义拆分字符串行的规则:
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
推荐阅读
- c# - 使用输入参数的 CSHTML 页面调用 void 方法
- promise - JS 承诺:如何链接 `then` 调用?
- android - 在 Firebase 数据库中上传图像期间,将错误的 URL 提取到数据库中。需要一些指导。(Kotlin)
- python - 打印方法“无效语法”反转字符串
- typescript - Typescript中类中所有函数的强制返回类型
- c++ - 序列化一个成员为向量的类
> 使用 boost:: 序列化 - angular7 - 无法构建项目
- python-3.x - 如何给函数一个参数而不在python中执行它?
- reactjs - 如何从日志文件而不是应用程序日志输出日志
- java - JUnit 测试类顺序