【问题标题】:Write expression to pickup specific content from a column using pandas使用 pandas 编写表达式以从列中提取特定内容
【发布时间】:2020-11-16 07:24:50
【问题描述】:

我想我可能要求的是不可能的。 我正在尝试从 Notes 列中提取以下内容并删除所有剩余的单词。 我希望抓取的格式是看起来像“0-0-0”或“0-0-0”的内容。但我写的表达式只是抓住了第 5 行和第 6 行。我将永远感激不尽。

import pandas as pd
import re as re

data = {'Notes':  ['1,088 errors  - 0 comments - 1109 pages', '76-0-143-SIS', 
                   '0 - 18 - 624  *flashcard questions (119 pgs PDF)', 
                   '0-0-1 page', '3 - 8 - 15  M1', '0 - 6 - 115', '35-0-100']}

QA_data = pd.DataFrame (data, columns = ['Notes'])

print (QA_data)

结果是这样的:

                                              Notes
0           1,088 errors  - 0 comments - 1109 pages
1                                      76-0-143-SIS
2  0 - 18 - 624  *flashcard questions (119 pgs PDF)
3                                        0-0-1 page
4                                    3 - 8 - 15  M1
5                                       0 - 6 - 115
6                                          35-0-100

我使用正则表达式来构建我的表达式,并使用 pandas 从字符串中提取必要的信息。

space = re.compile('^\d+ - \d+ - \d+$')
nospace = re.compile('^\d+-\d+-\d+$')
print(checker.match("123 -123 - 123"))

使用 for 循环匹配我的字符串并将其他所有内容替换为 ''。

task_dicts = QA_data.to_dict()
#print(task_dicts.keys())
#print(task_dicts["Notes"])
for keys in task_dicts["Notes"]:
    if not space.match(str(task_dicts["Notes"][keys])) and not space.match(str(task_dicts["Notes"][keys])):
        task_dicts["Notes"][keys] = ''

for keys in task_dicts["Notes"]:
   print(task_dicts["Notes"][keys])

【问题讨论】:

  • 为什么不删除所有空间..然后两个正则表达式成为一个
  • 这是您要找的吗? QA_data.loc[QA_data.Notes.str.contains(r'^\d\s?-\s?\d')](如果您发布所需的输出会有所帮助)

标签: python regex pandas for-loop pattern-matching


【解决方案1】:

在数组的每个元素上尝试这个正则表达式。不过,您必须自己删除空格。

([\d ]+-){2}[\d ]+

const regExpStr = String.raw`([\d ]+-){2}[\d ]+`;
const regExp = new RegExp(regExpStr, 'g');

const data = [
  '1,088 errors  - 0 comments - 1109 pages',
  '76-0-143-SIS',
  '0 - 18 - 624  *flashcard questions (119 pgs PDF)',
  '0-0-1 page',
  '3 - 8 - 15  M1', '0 - 6 - 115', '35-0-100'
];

const matches = data.map(datum => datum.match(regExp)?.[0]);

console.log(matches);

【讨论】:

    猜你喜欢
    • 2021-04-02
    • 2019-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-30
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多