Remove opening and closing parenthesis with word in pandas

前端 未结 4 856
庸人自扰
庸人自扰 2021-01-26 01:07

Given a data frame:

df = 

                         multi
0 MULTIPOLYGON(((3 11, 2 33)))
1 MULTIPOLYGON(((4 22, 5 66)))

I was trying to remov

4条回答
  •  一生所求
    2021-01-26 01:43

    Try this:

        import pandas as pd
    import re 
    def f(x):
        x = ' '.join(re.findall(r'[0-9, ]+',x))
        return x
    
    def f2(x):
        x = re.findall(r'[0-9, ]+',x)
    
        return pd.Series(x[0].split(','))       
    
    
    df =pd.DataFrame({'a':['MULTIPOLYGON(((3 11, 2 33)))' ,'MULTIPOLYGON(((4 22, 5 6)))']})
    df['a'] = df['a'].apply(f)
    print(df)
    #or for different columns you can do
    df =pd.DataFrame({'a':['MULTIPOLYGON(((3 11, 2 33)))' ,'MULTIPOLYGON(((4 22, 5 6)))']})
    #df['multi'] = df.a.str.replace('[^0-9. ]', '', regex=True)
    #print(df)
    list_of_cols = ['c1','c2']
    df[list_of_cols] = df['a'].apply(f2)
    del df['a']
    print(df)
    

    output:

                a
    0  3 11, 2 33
    1   4 22, 5 6
         c1     c2
    0  3 11   2 33
    1  4 22    5 6
    [Finished in 2.5s]
    

提交回复
热议问题