Python-正则表达式在数据帧中拆分数据

Python-正则表达式在数据帧中拆分数据,python,pandas,Python,Pandas,我有一个包含值的列。我想根据正则表达式进行拆分。如果正则表达式匹配,原始值将替换为拆分的左侧。新列将包含拆分的右侧 下面是一些示例代码。我觉得我很接近,但它不太起作用 import pandas as pd import re df = pd.DataFrame({ 'A' : ["test123","foo"]}) // Regex example to split it if it ends in numbers r = r"^(.+?)(\d*)$" df['A'], df['B']

我有一个包含值的列。我想根据正则表达式进行拆分。如果正则表达式匹配,原始值将替换为拆分的左侧。新列将包含拆分的右侧

下面是一些示例代码。我觉得我很接近,但它不太起作用

import pandas as pd
import re

df = pd.DataFrame({ 'A' : ["test123","foo"]})

// Regex example to split it if it ends in numbers
r = r"^(.+?)(\d*)$"

df['A'], df['B'] = zip(*df['A'].apply(lambda x: x.split(r, 1)))
print(df)
在上面的示例中,我希望得到以下输出

         A        B
0     test      123
1     foo

我对Python还相当陌生,并认为这将是一个方向。然而,我似乎还没有完全达到目的。有人能帮我纠正这个例子吗?

只需基于您自己的正则表达式即可

df.A.str.split(r,expand=True).replace('',np.nan).dropna(thresh=1,axis=1).fillna('')
Out[158]: 
      1    2
0  test  123
1   foo     


df[['A','B']]=df.A.str.split(r,expand=True).replace('',np.nan).dropna(thresh=1,axis=1).fillna('')
df
Out[160]: 
      A    B
0  test  123
1   foo     

只需基于您自己的正则表达式

df.A.str.split(r,expand=True).replace('',np.nan).dropna(thresh=1,axis=1).fillna('')
Out[158]: 
      1    2
0  test  123
1   foo     


df[['A','B']]=df.A.str.split(r,expand=True).replace('',np.nan).dropna(thresh=1,axis=1).fillna('')
df
Out[160]: 
      A    B
0  test  123
1   foo     
结果:

      A    B
0  test  123
1   foo   
结果:

      A    B
0  test  123
1   foo   

您的正则表达式工作正常,请将其与str.extract一起使用

df = pd.DataFrame({ 'A' : ["test123","foo", "12test3"]})
df[['A', 'B']] = df['A'].str.extract("^(.+?)(\d*)$", expand = True)


    A       B
0   test    123
1   foo 
2   12test  3

您的正则表达式工作正常,请将其与str.extract一起使用

df = pd.DataFrame({ 'A' : ["test123","foo", "12test3"]})
df[['A', 'B']] = df['A'].str.extract("^(.+?)(\d*)$", expand = True)


    A       B
0   test    123
1   foo 
2   12test  3

也许我遗漏了一些东西,但如何将其添加到A列和B列?我看到您提供的示例输出是第1列和第2列。如果我做df['A'],df['B']=yourCode,我得到的值是1和2,而不是expected@ekjcfn3902039已更新…您只需将其分配回可能我缺少某些内容,但如何将其添加到A列和B列?我看到您提供的示例输出是第1列和第2列。如果我做df['A'],df['B']=yourCode,我得到的值是1和2,而不是expected@ekjcfn3902039已更新…您只需要重新分配它