【发布时间】:2020-06-28 21:15:35
【问题描述】:
给定一个列表/一组标签
labels = {'rectangle', 'square', 'triangle', 'cube'}
和一个数据框df,
df = pd.DataFrame(['rectangle rectangle in my square cube', 'triangle circle not here', 'nothing here'], columns=['text'])
我想知道我的一组标签中的每个单词在数据框的文本列中出现了多少次,并创建一个新列,其中包含前 X 个(可能是 2 或 3 个)重复次数最多的单词。如果两个单词的重复次数相同,那么它们可以出现在列表或字符串中
输出:
pd.DataFrame({'text' : ['rectangle rectangle in my square cube', 'triangle circle not here', 'nothing here'], 'best_labels' : [{'rectangle' : 2, 'square' : 1, 'cube' : 1}, {'triangle' : 1, 'circle' : 1}, np.nan]})
df['best_labels'] = some_function(df.text)
【问题讨论】:
-
pd.DataFrame({'text' : ['rectangle rectangle in my square cube', 'triangle circle not here', 'nothing here'], 'best_labels' : [{'rectangle' : 2, 'square' : 1, 'cube' : 1}, {'triangle' : 1, 'circle' : 1}, np.nan]})是您拥有的东西,还是预期输出的一部分? -
为什么不在
best_labels中留下一个空集以应对没有匹配的情况?np.nan(“不是数字”)是一个奇怪的“默认”值,因为没有一个有效值是数字。
标签: python pandas dataframe count find-occurrences