python - 如何访问 re.findinter 输出对象中的数据?
问题描述
我想从我用 regex.findinter 生成的对象中访问“跨度”和“匹配”数据。但是我找不到如何将对象结构转换为 pandas df 以便我可以更轻松地操作它。
我可以遍历对象以打印数据。但是 regex.findinter 文档没有说明如何访问数据。我能找到的最好的是页面https://docs.python.org/2.0/lib/match-objects.html
我尝试将行附加到熊猫 df 但没有运气。见代码。它给出错误:TypeError:无法连接类型为“”的对象;只有 pd.Series、pd.DataFrame 和 pd.Panel(已弃用)obj 有效
import re
import pandas as pd
def find_rez(string):
regex = re.compile(r'\s\d{10}\s')
return(regex.finditer(string))
#open file with text data
file = open('prepaid_transactions_test2.txt')
text = file.read()
#get regex object with locations of all matches.
rez_mo = find_rez(text)
#Create empty df with span and match columns.
df = pd.DataFrame(columns=['span','match'])
#Append each row from object to pandas df. NOT WORKING.
for i in rez_mo:
df.append(i)
我想要一个以范围和匹配作为列的 pandas df。但我无法转换它看起来的类型。
解决方案
我刚刚找到了解决方案。可能不是最优雅的,但....它有效。
for i in rez_mo:
df.loc[len(df)]=[i.start()],[i.group()]
推荐阅读
- c - 转换 void* 缓冲区时无效使用 void 表达式
- spring - Spring - 避免混合版本
- windows - Windows 上的 Docker - 端口锁定
- mysql - 使用 xdevapi 和节点的 MySQL“未选择数据库”错误 (1046)
- javascript - 使用 onclick 和 eventlistener 关闭菜单的问题
- jenkins - Jenkins Pipeline 发布到 Perforce
- aws-lambda - CloudFormation CloudWatch Cron 未链接?
- events - kubernetes 不会在我的自定义资源上聚合事件
- c# - 将 Asp.net 核心控制器限制为特定域名
- python - 如何在数据框中的字符串中查找数字并使用千位分隔符重新格式化该数字?