【问题标题】:Extract only numbers and only string from pandas dataframe从熊猫数据框中仅提取数字和字符串
【发布时间】:2020-06-03 08:21:08
【问题描述】:

我试图只提取两个不同数据帧中的数字和字符串。我正在使用正则表达式来提取数字和字符串。

import pandas as pd

df_num = pd.DataFrame({
        'Colors': ['lila1.5', 'rosa2.5', 'gelb3.5', 'grün4', 'rot5', 'schwarz6', 'grau7', 'weiß8', 'braun9', 'hellblau10'],
        'Animals': ['hu11nd', '12welpe', '13katze', 's14chlange', 'vo15gel', '16papagei', 'ku17h', '18ziege', '19pferd',
                    'esel20']
    })

for column in df_num.columns:
    df_num[column] = df_num[column].str.extract('(\d+)').astype(float)

print(df_num)

我也尝试过使用'([\d+][\d+\.\d+])' and '([\d+\.\d+])'

在这里我得到了输出,但不是我所期望的。虽然我期待浮点数,但我没有得到 1.5 或 2.5。

我得到类似下图的东西:

df_str = pd.DataFrame({
        'Colors': ['lila1.5', 'rosa2.5', 'gelb3', 'grün4', 'rot5', 'schwarz6', 'grau7', 'weiß8', 'braun9', 'hellblau10'],
        'Animals': ['hu11nd', '12welpe', '13katze', 's14chlange', 'vo15gel', '16papagei', 'ku17h', '18ziege', '19pferd',
                    'esel20']
    })

for column in df_str.columns:
    df_str[column] = df_str[column].str.extract('([a-zA-Z]+)')

print(df_str)

在这种情况下,当数字在末尾或开头时,我会得到字符串,但如果数字放在中间或任何其他地方,那么我期望我不会得到结果。 当前输出如下图:

我认为我的正则表达式不正确。哪个是解决这些问题的正确正则表达式?或者有没有其他方法可以只提取熊猫数据框中的数字和字符串?

【问题讨论】:

标签: python-3.x pandas dataframe data-science text-extraction


【解决方案1】:

最简单的方法是定义一些函数:

def text(x):
    return x.str.replace(r'[0-9.]+','')
def values(x):
    return x.str.extract(r'([0-9.]+)', expand = False)

df_str.transform([text,values])

          Colors          Animals       
       text values      text values
0      lila    1.5      hund     11
1      rosa    2.5     welpe     12
2      gelb      3     katze     13
3      grün      4  schlange     14
4       rot      5     vogel     15
5   schwarz      6   papagei     16
6      grau      7       kuh     17
7      weiß      8     ziege     18
8     braun      9     pferd     19
9  hellblau     10      esel     20

【讨论】:

    【解决方案2】:

    您的代码在正确的轨道上,您只需要考虑小数和整数的可能性:

    df_num['colors_num'] = df_num.Colors.str.extract(r'(\d+[.\d]*)')
    df_num['animals_num'] = df_num.Animals.str.extract(r'(\d+[.\d]*)')
    df_num['colors_str'] = df_num.Colors.str.replace(r'(\d+[.\d]*)','')
    df_num['animals_text'] = df_num.Animals.str.replace(r'(\d+[.\d]*)','')
    
    
        Colors  Animals colors_num  animals_num colors_str  animals_text
    0   lila1.5 hu11nd  1.5 11  lila    hund
    1   rosa2.5 12welpe 2.5 12  rosa    welpe
    2   gelb3.5 13katze 3.5 13  gelb    katze
    3   grün4   s14chlange  4   14  grün    schlange
    4   rot5    vo15gel 5   15  rot vogel
    5   schwarz6    16papagei   6   16  schwarz papagei
    6   grau7   ku17h   7   17  grau    kuh
    7   weiß8   18ziege 8   18  weiß    ziege
    8   braun9  19pferd 9   19  braun   pferd
    9   hellblau10  esel20  10  20  hellblau    esel
    

    【讨论】:

      【解决方案3】:

      您可以使用(\d+\.\d+|\d+)extract 您的数字,并使用replace"" 的结果来获取您的字符串。

      print (df_num.assign(colors_num=df_num["Colors"].str.extract(r"(\d+\.\d+|\d+)"))
                   .assign(colors_col=df_num["Colors"].str.replace(r"(\d+\.\d+|\d+)","")))
      
             Colors     Animals colors_num colors_col
      0     lila1.5      hu11nd        1.5       lila
      1     rosa2.5     12welpe        2.5       rosa
      2     gelb3.5     13katze        3.5       gelb
      3       grün4  s14chlange          4       grün
      4        rot5     vo15gel          5        rot
      5    schwarz6   16papagei          6    schwarz
      6       grau7       ku17h          7       grau
      7       weiß8     18ziege          8       weiß
      8      braun9     19pferd          9      braun
      9  hellblau10      esel20         10   hellblau
      

      【讨论】:

        【解决方案4】:

        您可以利用内置的str 方法isnumeric()isalpha() 而不是正则表达式。见下文:

        # get rid of letters and handle floating points
        >>> "".join([c for c in "word234with23numbers" if c.isnumeric() or c == "."])
        "23423"
        
        >>> "".join([c for c in "gelb3.5" if c.isnumeric() or c == "."])
        "3.5"
        
        # get rid of numbers
        >>> "".join([c for c in "word234with23numbers" if c.isalpha()])
        "wordwithnumbers"
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-01-31
          • 2021-02-11
          • 2022-11-18
          • 2020-03-07
          • 1970-01-01
          • 2018-11-03
          相关资源
          最近更新 更多