首页 > 解决方案 > 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)')

谢谢你的帮助

标签: regexpandas

解决方案


为了避免过于复杂的正则表达式模式,也许您可​​以使用str.extractall获取所有数字,然后concat获取当前的 df。对于updown,使用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

推荐阅读