【问题标题】:Use a function over multiple columns在多列上使用函数
【发布时间】:2021-05-19 19:55:21
【问题描述】:

我需要将 wordcounter 函数应用于包含文本的多个列。我需要它看起来像这样:

我写的代码是

written = data.loc[:, 'text1':'text3']
written = written.fillna('none')

def wordcounter (text):
    count = text.str.split().str.len()
    return count

for col in written.columns:
    written[col + '_ct'] = written.apply(wordcounter, axis=1, args=(col,))

但我得到的错误是 TypeError: wordcounter() 接受 1 个位置参数,但给出了 2 个

有人知道我应该怎么做吗?谢谢!

【问题讨论】:

    标签: python pandas function loops text


    【解决方案1】:

    我认为您可以重新设计 apply 函数以将列不作为参数而是作为数据框过滤器使用:

    import pandas as pd
    
    
    def wordcounter(text):
        return len(text.split())
    
    
    data = pd.DataFrame.from_dict(
        {
            'text1': ['test words', 'more words'],
            'text2': ['words words', 'word'],
            'text3': ['words', 'word word'],
        }
    )
    
    written = data.loc[:, 'text1':'text3']
    written = written.fillna('none')
    
    for col in written.columns:
        written[col + '_ct'] = written[col].apply(wordcounter)
    
    print(written)
    

    输出

            text1        text2      text3  text1_ct  text2_ct  text3_ct
    0  test words  words words      words         2         2         1        
    1  more words         word  word word         2         1         2
    

    【讨论】:

      【解决方案2】:

      您可以apply 您的函数按列而不是按行,因为.str.split().str.len() 已经是“矢量化”操作。

      然后您可以将数据框(您原来的 text 以及 counts 一起组合成包含所有信息的最终数据框。

      def word_counter(series):
          return series.str.split().str.len()
      
      counts_df = (df.apply(word_counter)   # apply our function column-wise 
                     .add_suffix("_count")) # add a suffix of "_count" to the column names
      
      final_df = df.join(counts_df)         # combine the original dataframe with the counts
      
      print(final_df)
              text1        text2      text3  text1_count  text2_count  text3_count
      0  test words  words words      words            2            2            1
      1  more words         word  word word            2            1            2
      

      【讨论】:

        猜你喜欢
        • 2014-09-18
        • 2017-08-02
        • 1970-01-01
        • 2022-11-10
        • 2023-04-08
        • 1970-01-01
        • 1970-01-01
        • 2017-09-18
        • 1970-01-01
        相关资源
        最近更新 更多