【问题标题】:Count occurrences of letters in a word to pandas DataFrame计算单词中字母的出现次数到熊猫数据框
【发布时间】:2023-03-16 21:29:01
【问题描述】:

我有一个熊猫数据框,第一列中有单词。我想在同一个数据框中创建列,每个单词中每个字母的出现次数。

数据框应该类似于:

Word    A    B    C    D    E  ...  
BED     0    1    0    1    1 

有没有一种简单的方法可以做到这一点并针对添加到数据框中的新单词进行更新?如果字母不存在,它应该为它创建一个列

我试过了 -

for i in range(len(df)):
   u = df.iat[i, 0]
   for j in u:
      df.iat[i, j] = u.count(j)

没用……

【问题讨论】:

    标签: python python-3.x pandas dataframe


    【解决方案1】:

    您可以在列表理解中使用collections.Counter,然后使用string.ascii_uppercase 重新索引:

    from collections import Counter
    from string import ascii_uppercase
    
    df = df[['Word']].join(pd.DataFrame([Counter(word) for word in df['Word'].str.upper()])
                           .reindex(list(ascii_uppercase), axis=1).fillna(0).astype(int))
    

    [输出]

    print(df)
    
      Word  A  B  C  D  E  F  G  H  I  ...  Q  R  S  T  U  V  W  X  Y  Z
    0  BED  0  1  0  1  1  0  0  0  0  ...  0  0  0  0  0  0  0  0  0  0
    
    [1 rows x 27 columns]
    

    【讨论】:

    • 这行代码很棒,以后肯定会用到。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-13
    • 1970-01-01
    • 2023-03-13
    • 2018-03-28
    • 1970-01-01
    • 2013-12-10
    • 1970-01-01
    相关资源
    最近更新 更多