【问题标题】:Remove opening and closing parenthesis with word in pandas删除熊猫中单词的左括号和右括号
【发布时间】:2019-11-03 12:34:58
【问题描述】:

给定一个数据框:

df = 

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

我试图删除单词 'MULTIPOLYGON' 和括号 '(((', ')))'


我的尝试:

df['multi'] = df['multi'].str.replace(r"\(.*\)","")
df['multi'] = df['multi'].map(lambda x: x.lstrip('MULTIPOLYGON()').rstrip('aAbBcC'))

df.values = 

array([[''],
       [''],
       ...
       [''],
       [''],
       [''],
       ['7.5857754821 44.9628409423']

期望的输出:

df = 

     multi
3 11, 2 33
 4 22, 5 6

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    试试这个:

        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)
    

    输出:

                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]
    

    【讨论】:

    • 你几乎回答了我的第二个问题!但是如果列数超过 100 怎么办?
    • 对不起,我在样本数据中做错了。它们之间有一个逗号,我想删除除逗号以外的所有内容
    【解决方案2】:

    您还可以将str.replace 与正则表达式一起使用:

    # removes anything that's not a digit or a space or a dot
    df['multi'] = df.multi.str.replace('[^0-9\. ]', '', regex=True)#changing regex
    

    【讨论】:

      【解决方案3】:

      您可以通过以下方式使用 df.column.str。

      df['a'] = df['a'].str.findall(r'[0-9.]+')
      df = pd.DataFrame(df['a'].tolist())
      print(df)
      

      输出:

           0     1
      0  3.49  11.10
      1  4.49  22.12
      

      这适用于任意数量的列。但最后你必须为这些列命名。

      df.columns = ['a'+str(i) for i in range(df.shape[1])]
      

      即使某些行具有不同数量的数值,此方法也有效。喜欢

      df =pd.DataFrame({'a':['MULTIPOLYGON(((3.49)))' ,'MULTIPOLYGON(((4.49 22.12)))']})
      
           a
       0  MULTIPOLYGON(((3.49)))
       1  MULTIPOLYGON(((4.49 22.12)))
      

      所以预期的输出是

            0     1
      0   3.49    None
      1   4.49    22.12
      

      使用命名列后,

      df.columns = ['a'+str(i) for i in range(df.shape[1])]
      

      你明白了,

            a0    a1
      0   3.49    None
      1   4.49    22.12
      

      【讨论】:

        【解决方案4】:

        Apply 在pandas 中是一个相当慢的方法,因为它基本上是一个循环遍历每一行并应用你的函数。 Pandas 有向量化的方法,我们可以在这里使用str.extract 来提取你的模式:

        df['multi'] = df['multi'].str.extract('(\d\.\d+\s\d+\.\d+)')
        
                multi
        0  3.49 11.10
        1  4.49 22.12
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-10-12
          • 2017-04-20
          • 2019-02-03
          • 1970-01-01
          • 2016-08-26
          • 1970-01-01
          • 2022-12-17
          • 1970-01-01
          相关资源
          最近更新 更多