我有一个数据框df
,由两列组成(单词和该单词的含义/定义)。我想对单词的每个定义使用 Collections.Counter 对象,并以尽可能最 Pythonic 的方式计算定义中单词出现的频率。
传统方法是使用 iterrows()
方法迭代数据帧并进行计算。
示例输出
<table style="height: 59px;" border="True" width="340">
<tbody>
<tr>
<td>Word</td>
<td>Meaning</td>
<td>Word Freq</td>
</tr>
<tr>
<td>Array</td>
<td>collection of homogeneous datatype</td>
<td>{'collection':1,'of':1....}</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>
最佳答案
我会利用 Pandas str
访问器方法并执行此操作
from collections import Counter
Counter(df.definition.str.cat(sep=' ').split())
一些测试数据
df = pd.DataFrame({'word': ['some', 'words', 'yes'], 'definition': ['this is a definition', 'another definition', 'one final definition']})
print(df)
definition word
0 this is a definition some
1 another definition words
2 one final definition yes
然后按空格连接和分割并使用 Counter
Counter(df.definition.str.cat(sep=' ').split())
Counter({'a': 1,
'another': 1,
'definition': 3,
'final': 1,
'is': 1,
'one': 1,
'this': 1})
关于python - 如何编写最有效的方法来为 dataframe python 中的列添加值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41512293/