Raj*_*til 4 python dataframe python-3.x pandas
我有一个熊猫数据框,第一列中有单词。我想在同一数据框中创建列,其中包含每个单词中每个字母的出现次数。
数据框应该类似于:
Word A B C D E ...
BED 0 1 0 1 1
Run Code Online (Sandbox Code Playgroud)
有没有一种简单的方法可以做到这一点并更新它以添加到数据框中的新单词?如果该字母不存在,它应该为该字母创建一个列
我试过这个 -
for i in range(len(df)):
u = df.iat[i, 0]
for j in u:
df.iat[i, j] = u.count(j)
Run Code Online (Sandbox Code Playgroud)
不起作用...
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))
Run Code Online (Sandbox Code Playgroud)
[输出]
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]
Run Code Online (Sandbox Code Playgroud)