regex - Pandas 和 reg ex,将文本和数字分解为带有标题的几列
问题描述
我有一个包含一列的数据框:
1 Tile 1 up Red 2146 (75) Green 1671 (75)
数字 1 最多 10 向上也可以向下 2146 和 1671 可以是 9999 以内的任何数字
在不使用拆分的情况下将这些中的每一个分成单独的列的最佳方法是什么?我正在查看正则表达式,但不确定如何处理(尤其是空格)。我也喜欢加入新列名的想法,并从
Pixel.str.extract(r'(?P<num1>\d)(?P<text>[Tile])(?P<Tile>\d)')
谢谢你的帮助
解决方案
为了避免过于复杂的正则表达式模式,也许您可以使用str.extractall
获取所有数字,然后concat
获取当前的 df。对于up
或down
,使用str.findall
:
df = pd.DataFrame({"title":["1 Tile 1 up Red 2146 (75) Green 1671 (75)",
"10 Tile 10 down Red 9999 (75) Green 9999 (75)"]})
df = pd.concat([df, df["title"].str.extractall(r'(\d+)').unstack().loc[:,0]], axis=1)
df["direction"] = df["title"].str.findall(r"\bup\b|\bdown\b").str[0]
print (df)
#
title 0 1 2 3 4 5 direction
0 1 Tile 1 up Red 2146 (75) Green 1671 (75) 1 1 2146 75 1671 75 up
1 10 Tile 10 down Red 9999 (75) Green 9999 (75) 10 10 9999 75 9999 75 down
推荐阅读
- tensorflow - 张量流中是否有原生的“MinMaxScaler”?
- python - 在 Python Tkinter 中单击它会打开一个新的 Tk() 窗口的按钮
- kubernetes - 部署入口控制器时 Kubernetes API 超时
- html - Parent node in react-testing-library
- spring-boot - 如何使用 Kubernetes Ingress 执行自定义身份验证
- jquery - HereMap:在位置上悬停时移动地图
- python - 如何从 lambda aws -python 传递电子邮件正文中的变量
- python - Git Bash 没有按 python 2.7.18 的顺序处理我的打印语句和 raw_inputs
- intellij-idea - “将控制台输出保存到日志文件”在 IDEA 中不起作用
- sql - 获取以下条目不是+1分钟的所有条目