【问题标题】:Word length count with for/if loop pandasfor/if 循环 pandas 的字长计数
【发布时间】:2021-07-27 07:20:38
【问题描述】:

我有一个数据框,我需要根据Note 列分别计算每个ConceptWord 的字长。

For each Concept in a df: 
  if Note contains ("tupi") -> count word length for these Words.    
  if not -> count word length for others

  print (Concept + " tupi " + word_length)
  print (Concept + " not tupi " + word_length)

输出应该是这样的:

ANTEATER tupi 5.034

ANTEATER not tupi 4.56
_______
WILD CAT tupi 4.55

WILD CAT not tupi 3.44

输入数据框示例:

Language Concept Word Borrowing Note
First ANTEATER tamanduá YES loan from tupi
Second ANTEATER uãiarú
Third ANTEATER atãn
Fourth ANTEATER aatãm YES loan from tupi
Fifth WILD CAT tamano YES
Sixth WILD CAT sdfsg YES
Seventh WILD CAT tamano YES loan from tupi
Eigth WILD CAT sdfsg YES loan from tupi

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您可以完全在 pandas 中完成此操作,而无需 for 循环。

    • 创建一个列tupi,表示Note 列是否包含“tupi”。
    • 使用Word 列中单词的长度创建一个Word Length 列。

    现在,使用groupby 并计算Note 列中带有和不带有“tupi”的每个Concept 的平均字长:

    df['tupi'] = df['Note'].str.contains('tupi').fillna(False)
    df['Word Length'] = df['Word'].str.len()
    df.groupby(['Concept', 'tupi'])['Word Length'].mean()
    

    来自给定数据的结果数据框:

    Concept   tupi 
    ANTEATER  False    5.0
              True     6.5
    WILD CAT  False    5.5
              True     5.5
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-24
      • 2021-07-30
      • 2017-10-22
      • 2017-08-31
      • 2017-07-21
      • 2020-03-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多