【问题标题】:Find Last Word in a String within a List (Pandas, Python 3)在列表中的字符串中查找最后一个单词(Pandas,Python 3)
【发布时间】:2014-09-17 21:06:38
【问题描述】:

我有一个名为“Stories”的 DF,如下所示:

Story
The Man
The Man Child
The Boy of Egypt
The Legend of Zelda

有没有办法提取每个字符串中的最后一个单词?

类似:

Stories['Prefix'] = final['Story'].str.extract(r'([^ ]*)') 

找到前缀,但我不确定如何相应地调整它

我希望最终得到类似的东西

Story                  Suffix
The Word Of Man         Man
The Man of Legend       Legend
The Boy of Egypt        Egypt
The Legend of Zelda     Zelda

任何帮助将不胜感激!

【问题讨论】:

    标签: python-3.x pandas


    【解决方案1】:

    您可以使用.str 两次,因为.str[-1] 将拾取最后一个元素:

    >>> df["Suffix"] = df["Story"].str.split().str[-1]
    >>> df
                     Story Suffix
    0              The Man    Man
    1        The Man Child  Child
    2     The Boy of Egypt  Egypt
    3  The Legend of Zelda  Zelda
    

    【讨论】:

    • 如果字符串中只有一个单词怎么办?我们不希望那样。我们如何将其包含在条件中?
    【解决方案2】:

    我认为 split 比正则表达式更清晰一点,但您可以apply 任何您选择的系列函数。

    final['Prefix'] = final['Story'].apply(lambda x: x.split()[-1])
    

    【讨论】:

      【解决方案3】:

      要获得最后一个单词,您可以创建一个列表,其中每个标题都是列表中的一个条目,并调用此列表推导式来获取所有后缀:

      suffixes = [item.split()[-1] for item in mylist]
      

      这会按每个单词拆分字符串,并使用[-1] 获取最后一个条目。

      然后你可以随心所欲地写回去。

      上面的列表推导等价于:

      suffixes = []
      for item in mylist:
          suffixes.append(item.split()[-1])) #item.split() to get a list of each word in the string, and [-1] to get the last word
      

      这是一个例子:

      mylist = ['The Man', 'The Man Child', 'The Boy of Egypt', 'The Legend of Zelda']
      suffixes = [item.split()[-1] for item in mylist]
      print suffixes #['Man', 'Child', 'Egypt', 'Zelda']
      

      【讨论】:

      • 嗨,我不确定我是否遵循这个逻辑——你能提供更多细节吗?仍在学习列表理解的方法。谢谢!
      【解决方案4】:

      不确定是否有任何内置函数可以直接执行此操作。您可以遍历字符串,如

      for i in xrange(len(df)):
          df['Suffix'].iat[i] = df['Story'].iat[i].split(' ')[len(df['Story'].iat[i].split(' '))-1]
      

      【讨论】:

        【解决方案5】:

        使用可以使用正则表达式模式来提取最后一个单词:

        In [10]:
        
        df['suffix'] = df.Story.str.extract(r'((\b\w+)[\.?!\s]*$)')[0]
        df
        Out[10]:
                          Story  suffix
        0               The Man     Man
        1         The Man Child   Child
        2      The Boy of Egypt   Egypt
        3  The Legend of Zeldar  Zeldar
        

        该模式是我在这里找到的答案的修改版本:regex match first and last word or any word

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-08-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多