使用正则表达式或模式匹配将字符串规则转换为python中的数据帧



我们如何将以下字符串规则转换为结构化数据帧?

我的输入是一个字符串(本质上是一个规则(,下面是一个输入字符串的例子:

当男性身高(英寸(<=2.30&amp;女性身高(英寸(>1&amp;男性体重(公斤(<=350&amp;男性体重(公斤(<=349 THEN最终输出=[[75]]

结果数据帧应该看起来像:

Variable                      Sign       Value
Male Height (inches)          <=          2.30
Female Height (inches)         >           1
Male Weight (kgs)             <=          350
Male Weight (kgs)             <=          349
Final Output                   =          75

其中变量对应于规则中的X1..Xn,符号及其值是隐式的。数据帧中的最终值是Y,它是规则中"THEN"之后的变量。

您可以使用pandas:执行regex

pattern = pattern = '(?P<Variable>[^A-Z<>=&]+)s?(?P<Sign>[<>=]+)W*(?P<Value>[d.]+)'
pd.Series(s).str.extractall(pattern)

输出:

Variable Sign Value
match                                     
0 0         male height (inches)    <=  2.30
1       female height (inches)     >     1
2            male weight (kgs)    <=   350
3            male weight (kgs)    <=   349
4                 final output     =    75

先执行explode,然后执行多个splits是您的字符串:

df=pd.Series(s).str.split(' THEN ').explode().str.strip('WHEN ').str.split(' && ').explode().str.split(' ',expand=True)
0   1       2
0  X1  <=    2.30
0  X2   >       1
0  X3  <=     350
0  X3  <=     349
0  X2   >       1
0   Y   =  [[75]]

最新更新