gpt4 book ai didi

python - 如何获得按第二个变量分组的词频计数(Python)

转载 作者:行者123 更新时间:2023-12-04 09:43:30 25 4
gpt4 key购买 nike

我是 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'])


最佳答案

数据

df=pd.DataFrame({'Property':['House','Car','Car','House','Car'],'Description':['Blue,Two stories,pool','Green,Dented,Manual,New','Blue,Automatic,Heated Seat','Blue,Furnished,HOA','Blue,Old,Multiple Owners']})

链式解决方案 df.assign(words=df.Description.str.lower().str.split(',')).explode('words').groupby( '属性')['单词'].value_counts()

分解解释

#Create list

df['words'] = df.Description.str.lower().str.split(',')

#Explode and count

df=df.explode('words').groupby('Property')['words'].value_counts()

Property words
Car blue 2
automatic 1
dented 1
green 1
heated seat 1
manual 1
multiple owners 1
new 1
old 1
House blue 2
furnished 1
hoa 1
pool 1
two stories 1
Name: words, dtype: int64

关于python - 如何获得按第二个变量分组的词频计数(Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62226479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com