【问题标题】:Moving row values contains specific string to new column in Python移动行值包含特定字符串到 Python 中的新列
【发布时间】:2020-03-29 01:49:59
【问题描述】:

我正在重构数据框。示例数据框如下:

df = pd.DataFrame()
df ['Stats'] = ['Def duels', 'Def duels Won','Back passes', 'Back passes[Acc]','Dribbles', 'Dribbles[Suc]']
df ['Value'] = [5,2.5,60,55,5,2]

我想创建一个只包含字符串的新列,例如“Won”、“Acc”和“Suc”。预期的数据框如下:

我可以尝试什么来解决这个问题?

【问题讨论】:

    标签: python string pandas shift


    【解决方案1】:

    IIUC

    s=df.Stats.str.contains('Won|Acc|Suc')
    df['New']=df.Stats.where(s,'')
    df.Stats=df.Stats.mask(s,'')
    df
             Stats  Value               New
    0    Def duels    5.0                  
    1                 2.5     Def duels Won
    2  Back passes   60.0                  
    3                55.0  Back passes[Acc]
    4     Dribbles    5.0                  
    5                 2.0     Dribbles[Suc]
    

    【讨论】:

      【解决方案2】:

      解决方案:

      # initialize Stats1 with empty strings
      df['Stats1'] = ''
      
      # copy values from `Stats`
      df.iloc[1::2,-1] = df['Stats']
      
      # replace the copied values with empty strings
      df['Stats'] = np.where(df['Stats1'].ne(''), '', df['Stats'])
      

      输出:

               Stats  Value            Stats1
      0    Def duels    5.0                  
      1                 2.5     Def duels Won
      2  Back passes   60.0                  
      3                55.0  Back passes[Acc]
      4     Dribbles    5.0                  
      5                 2.0     Dribbles[Suc]
      

      【讨论】:

        【解决方案3】:

        使用str.containsnp.where

        df['stat1'] = np.where(df['Stats'].str.contains('won|acc|suc',case=False),df['Stats'],'')
        df['Stats'] = np.where(df['Stats'].str.contains('won|acc|suc',case=False),'',df['Stats'])
        
        
        print(df)
        
                 Stats  Value             stat1
        0    Def duels    5.0                  
        1                 2.5     Def duels Won
        2  Back passes   60.0                  
        3                55.0  Back passes[Acc]
        4     Dribbles    5.0                  
        5                 2.0     Dribbles[Suc]
        

        【讨论】:

        • 大家好,非常感谢您的帮助。非常感谢。
        猜你喜欢
        • 2021-12-01
        • 2019-10-13
        • 2022-11-10
        • 2020-03-25
        • 1970-01-01
        • 2023-02-23
        • 1970-01-01
        • 2015-10-17
        • 1970-01-01
        相关资源
        最近更新 更多