【问题标题】:Dynamic column assignment in Python PandasPython Pandas 中的动态列分配
【发布时间】:2021-11-20 17:03:30
【问题描述】:

我有一个 pandas 数据框,我想从中创建一些与文本相关的特征列。我还有一个计算这些特征的类。这是我的代码:

r = ReadabilityMetrics()
text_features = [['sentence_count', r.sentence_count], ['word_count', r.word_count], ['syllable_count', r.syllable_count], ['unique_words', r.unique_words],
               ['reading_time', r.reading_time], ['speaking_time', r.speaking_time], ['flesch_reading_ease', r.flesch_reading_ease], ['flesch_kincaid_grade', r.flesch_kincaid_grade], 
                 ['char_count', r.char_count]]

(df
 .assign(**{t:df['description'].apply(f) for t, f in text_features})
)

我遍历 text_features 以动态创建列。

我的问题:如何删除对方法的引用并使text_features 更简洁?

例如,我想要text_features = ['sentence_count', 'word_count', 'syllable_count', ...],由于列名与函数名相同,因此动态引用函数。拥有一个嵌套列表似乎并不干燥,因此寻找更有效的实现。

【问题讨论】:

    标签: python pandas lambda iteration list-comprehension


    【解决方案1】:

    我想你正在寻找这个:

    text_features = ['sentence_count', 'word_count', 'syllable_count', 'unique_words', 'reading_time', 'speaking_time', 'flesch_reading_ease', 'flesch_kincaid_grade', 'char_count']
    
    df.assign(**{func_name: df['description'].apply(getattr(r, func_name)) for func_name in text_features})
    

    【讨论】:

      【解决方案2】:
      for column_name, function in text_features:
          df[column_name] = df['description'].apply(function)
      

      我认为这很好。我可能会将text_features 定义为元组列表而不是列表列表。

      如果您确定它必须更简洁,请将text_features 定义为字符串列表。

      for column name in text_features:
          df[column_name] = df['description'].apply(getattr(r, column_name))
      

      我不会尝试使它比这更简洁(例如使用带有字典的**)以使解决方案不那么深奥,但这只是一个见仁见智的问题。

      【讨论】:

        【解决方案3】:

        在你的情况下尝试getattr

        (df
         .assign(**{t:df['description'].apply(getattr(r, t)()) for t in text_features})
        )
        

        【讨论】:

          猜你喜欢
          • 2021-05-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-07-12
          • 2018-05-06
          • 1970-01-01
          • 2016-03-09
          • 2020-09-23
          相关资源
          最近更新 更多