python - 如何获得按第二个变量(Python)分组的词频计数
问题描述
我是 Python 的新手,所以很可能我只是没有正确地措辞来找到答案。
使用 Pandas,我能够在数据的描述字段中为每条记录找到最常见的 N 个单词。但是,我有两列;分类列和描述字段。如何找到每个类别最常见的词?
防爆数据:
- Property|Description
- House| Blue, Two stories, pool
- Car| Green, Dented, Manual, New
- Car| Blue, Automatic, Heated Seat
- House|New, Furnished, HOA
- Car|Blue, Old, Multiple Owners
我当前的代码将返回 Blue=3、New=2 等。但我需要知道的是 Blue 出现在 Car 一词中两次,而在 House 中出现一次。
当前相关代码
words = (data.Description.str.lower().str.cat(sep=' ').split())
keywords=pandas.DataFrame(Counter(words).most_common(10), columns=['Words', 'Frequency'])
解决方案
试试这个,按分隔符拆分行值,然后应用explode将列表中的每个元素转换为一行,最后是Groupby
# remove leading white space's & split by delimiter
df['Description'] = df['Description'].str.strip()\
.str.replace(",\s+", ",")\
.str.split(',')
# apply group by to get count of each word.
print(df.explode(column='Description').
groupby(["Property","Description"]).size().reset_index(name='count'))
输出,
Property Description count
0 Car Automatic 1
1 Car Blue 2
2 Car Dented 1
3 Car Green 1
4 Car Heated Seat 1
...
推荐阅读
- javascript - 绕过 XSS 的 HTML 编码/转义
- python - Keras LSTM 的输入转换
- javascript - Chrome 扩展程序 | 如何制作一个检查网站是否未加载(未完成加载)的功能?
- android - 我得到了 Expected BEGIN_ARRAY 但在第 1 行第 2 列路径 $ 尝试使用 Retrofit 在 Android (java) 中获取 json 时是 BEGIN_OBJECT
- html - 将粉色 div 放在银色 div 后面,确保我们可以在完成后悬停粉色 div
- java - 如何从 jHipster 中的 SecurityContextHolder 检索自定义 UserDetails?
- c# - reader.EndOfStream 未检测到流的结尾
- swift - 为什么我的 Objective-C 块在传递给 Swift 函数时没有显示?
- meteor - 覆盖或禁用 DEFAULT_PASSWORD_ENROLL_TOKEN_EXPIRATION_DAYS?
- macos - 什么是英特尔 MKL 致命错误:无法加载 libmkl_core.dylib。在 MacOs 中运行 pyspark 时?