【问题标题】:How to apply string methods to multiple columns of a dataframe如何将字符串方法应用于数据框的多列
【发布时间】:2019-02-05 12:27:35
【问题描述】:

我有一个包含多个字符串列的数据框。我想使用对数据框多列上的系列有效的字符串方法。像这样的东西是我想要的:

df = pd.DataFrame({'A': ['123f', '456f'], 'B': ['789f', '901f']})
df

Out[15]: 
      A     B
0  123f  789f
1  456f  901f

df = df.str.rstrip('f')
df
Out[16]: 
     A    B
0  123  789
1  456  901

显然,这不起作用,因为 str 操作仅对 pandas Series 对象有效。执行此操作的合适/最适合熊猫的方法是什么?

【问题讨论】:

    标签: python string pandas


    【解决方案1】:

    函数rstripSeries 一起使用,因此可以使用apply

    df = df.apply(lambda x: x.str.rstrip('f'))
    

    或由stack 和最后一个unstack 创建Series

    df = df.stack().str.rstrip('f').unstack()
    

    或者使用applymap:

    df = df.applymap(lambda x: x.rstrip('f'))
    

    如果需要,最后将函数应用于某些列:

    #add columns to lists
    cols = ['A']
    df[cols] = df[cols].apply(lambda x: x.str.rstrip('f'))
    df[cols] = df[cols].stack().str.rstrip('f').unstack()
    df[cols] = df[cols].stack().str.rstrip('f').unstack()
    

    【讨论】:

      【解决方案2】:

      您可以使用replaceregex=True 来模仿rstrip 的行为,它可以应用于整个DataFrame

      df.replace(r'f$', '', regex=True)
      

           A    B
      0  123  789
      1  456  901
      

      由于rstrip 需要一个字符序列来剥离,您可以轻松地扩展它:

      df.replace(r'[abc]+$', '', regex=True)
      

      【讨论】:

        【解决方案3】:

        您可以使用字典理解并提供给pd.DataFrame 构造函数:

        res = pd.DataFrame({col: [x.rstrip('f') for x in df[col]] for col in df})
        

        目前,Pandas str 方法效率低下。正则表达式效率更低,但更容易扩展。与往常一样,您应该使用数据进行测试。

        # Benchmarking on Python 3.6.0, Pandas 0.19.2
        
        def jez1(df):
            return df.apply(lambda x: x.str.rstrip('f'))
        
        def jez2(df):
            return df.applymap(lambda x: x.rstrip('f'))
        
        def jpp(df):
            return pd.DataFrame({col: [x.rstrip('f') for x in df[col]] for col in df})
        
        def user3483203(df):
            return df.replace(r'f$', '', regex=True)
        
        df = pd.concat([df]*10000)
        
        %timeit jez1(df)         # 33.1 ms per loop
        %timeit jez2(df)         # 29.9 ms per loop
        %timeit jpp(df)          # 13.2 ms per loop
        %timeit user3483203(df)  # 42.9 ms per loop
        

        【讨论】:

          猜你喜欢
          • 2021-05-14
          • 2020-11-23
          • 2021-12-22
          • 1970-01-01
          • 1970-01-01
          • 2011-05-20
          相关资源
          最近更新 更多