python - 如何编写最有效的方法来为 dataframe python 中的列添加值?

标签 python pandas dataframe

我有一个数据框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>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</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/

相关文章:

r - 如何使用预定义布局保存 igraph 对象的边列表?

pandas - 使用 pandas 加载波士顿数据集

python - 如何检查pyspark数据框中的字符串列是否全部为数字

python - 在运行时重置/重新加载嵌套类的类属性

python - sklearn中KMeans的变换是否可以逆转?

python - 如何处理 CSV 文件中 DECIMAL 列的缺失值

python-3.x - Python为多级索引的每组选择不同的行数

python - 对齐多年的日常数据

python获取具有k个元素的数组的最大偶数和

r - 为什么 data.table 上的 class(.SD) 显示 "data.frame"?