【问题标题】:How to reverse strings in pandas dataframe?如何反转熊猫数据框中的字符串?
【发布时间】:2019-10-21 21:38:01
【问题描述】:

我的数据框是这样的,

ID   col1
1    Michael Owen
2    Stephen Curry
3    Messi, Lionel
4    James, LeBron

我试图颠倒那些被", "分割的名字的顺序。

我的代码是,

df['col1'] = df.col1.str.split().apply(lambda x: ', '.join(x[::-1]))

但即使名称被" " 分割,它也会反转所有行。

ID   col1
1    Owen, Michael
2    Curry, Stephen
3    Lionel, Messi
4    LeBron, James

然后我尝试了

df.loc[df['col1'].str.contains(", ").split("col1")].apply(lambda x: ', '.join(x[::-1]))

它给了我一个错误,

AttributeError: 'Series' object has no attribute 'split'

我该如何解决这个问题?

【问题讨论】:

标签: python string pandas dataframe


【解决方案1】:

使用Series.where:

df['col1']=( df.col1.str.split()
              .apply(lambda x: ', '.join(x[::-1]).rstrip(','))
              .where(df['col1'].str.contains(','),df['col1']) )

   ID           col1
0   1   Michael Owen
1   2  Stephen Curry
2   3  Lionel, Messi
3   4  LeBron, James

如果你想放弃','

df['col1']=( df.col1.str.split()
              .apply(lambda x: ', '.join(x[::-1]).rstrip(','))
              .where(df['col1'].str.contains(','),df['col1']) 
              .str.replace(',','') )

   ID           col1
0   1   Michael Owen
1   2  Stephen Curry
2   3  Lionel  Messi
3   4  LeBron  James

【讨论】:

    【解决方案2】:

    它给了我一个错误,

    这是因为str.contains(", ") 返回一个布尔系列,它没有方法split

    无论如何,试试

    df.col1.str.split(',').str[1] + ',' + df.col1.str.split(',').str[0]
    

    【讨论】:

      【解决方案3】:

      修复你的代码np.where

      df['col1']=np.where(df.col1.str.contains(','),df.col1.str.split(', ').apply(lambda x: ', '.join(x[::-1])),df.col1)
      

      【讨论】:

        【解决方案4】:

        您只需在split() 中添加一个逗号,如下所示:

        df['col1'] = df.col1.str.split(',').apply(lambda x: ', '.join(x[::-1]))
        

        如果您想反转并删除 ',',请将其从 join 方法中删除。

        df['col1'] = df.col1.str.split(',').apply(lambda x: ' '.join(x[::-1]))
        

        【讨论】:

          【解决方案5】:

          我选择不使用逗号来表示最终值。如果需要逗号,请将join 字符串从' ' 更改为', '。我添加这些答案是因为:

          1. str[::-1] 完成这项工作时,无需使用apply 来反转列表
          2. 在以逗号分割时无需使用apply 或任何其他技巧',' 将生成一个列表,并且反转一个元素列表是相同的列表。这意味着我的方法可以安全地在没有逗号的名称上运行。我不需要 if/then 构造。
          3. 我以两种不同的方式处理潜在空间。
            1. 使用正则表达式
            2. str.strip

          正则表达式和pandas.Series.str ...

          ...链接了 3 次

          #                          regex expression  
          #                          split on comma
          #                          followed by zero
          #                          or more spaces
          #                               /--\
          df['col1'] = df.col1.str.split(',\s*').str[::-1].str.join(' ')
          
          df
          
             ID           col1
          0   1   Michael Owen
          1   2  Stephen Curry
          2   3   Lionel Messi
          3   4   LeBron James
          

          领悟和str.strip

          df['col1'] = [' '.join([*map(str.strip, x.split(','))][::-1]) for x in df.col1]
          
          df
          
             ID           col1
          0   1   Michael Owen
          1   2  Stephen Curry
          2   3   Lionel Messi
          3   4   LeBron James
          

          【讨论】:

            猜你喜欢
            • 2018-01-02
            • 2023-01-18
            • 2019-04-16
            • 2017-02-24
            • 2018-09-24
            • 1970-01-01
            • 2023-03-14
            • 2015-09-24
            • 2019-08-02
            相关资源
            最近更新 更多