计算可以包含在由全局和单行规模的字符串列表组成的 DataFrame 列中的集合词的出现次数
Count occurences of set words that can be contained in a DataFrame column composed by a list of strings on a global and single row scale
我希望我没有创建重复的笑声,但我花了几个小时寻找与我的问题类似的东西:)
这么说,我有以下输入:
foo= {"Brand":["loc doc poc",
"roc top mop",
"loc lot not",
"roc lot tot",
"loc bot sot",
"nap rat sat"] }
word_list=["loc","top","lot"]
df=pd.DataFrame(foo)
2 期望输出
1 包含出现次数的字典
2 包含每行出现次数的新列
#Outputs:
counter_dic={"loc":3,"top":1,"lot":2}
Brand count
0 loc doc poc 1
1 roc top mop 1
2 loc lot not 2
3 roc lot tot 1
4 toc bot sot 1
5 nap rat sat 0
我唯一的想法:
- 计算一组术语出现的次数。我可以创建一个词袋,然后根据字典键进行过滤吗?
如果找到类似的问题,显然可以关闭。
我检查了以下几个
Python Lists Finding The Number Of Times A String Occurs
这是一个潜在的解决方案,使用 str.count
创建一个临时计数数据帧,这将有助于两个输出。
df_counts = pd.concat([df['Brand'].str.count(x).rename(x) for x in word_list], axis=1)
看起来像:
loc top lot
0 1 0 0
1 0 1 0
2 1 0 1
3 0 0 1
4 1 0 0
5 0 0 0
1 - 存储出现次数的字典
df_counts.sum().to_dict()
[出局]
{'loc': 3, 'top': 1, 'lot': 2}
2 - 包含每行出现次数的新列
df['count'] = df_counts.sum(axis=1)
[出局]
Brand count
0 loc doc poc 1
1 roc top mop 1
2 loc lot not 2
3 roc lot tot 1
4 loc bot sot 1
5 nap rat sat 0
这是一种将计数转化为字典形式的方法:
df['Brand'].str.split(' ').explode().to_frame('Brand').groupby('Brand').size().loc[word_list].to_dict()
这是获取计数的方法:
df['count'] = df['Brand'].str.get_dummies(sep=' ').loc[:,word_list].sum(axis=1)
我希望我没有创建重复的笑声,但我花了几个小时寻找与我的问题类似的东西:)
这么说,我有以下输入:
foo= {"Brand":["loc doc poc",
"roc top mop",
"loc lot not",
"roc lot tot",
"loc bot sot",
"nap rat sat"] }
word_list=["loc","top","lot"]
df=pd.DataFrame(foo)
2 期望输出
1 包含出现次数的字典
2 包含每行出现次数的新列
#Outputs:
counter_dic={"loc":3,"top":1,"lot":2}
Brand count
0 loc doc poc 1
1 roc top mop 1
2 loc lot not 2
3 roc lot tot 1
4 toc bot sot 1
5 nap rat sat 0
我唯一的想法:
- 计算一组术语出现的次数。我可以创建一个词袋,然后根据字典键进行过滤吗?
如果找到类似的问题,显然可以关闭。
我检查了以下几个
Python Lists Finding The Number Of Times A String Occurs
这是一个潜在的解决方案,使用 str.count
创建一个临时计数数据帧,这将有助于两个输出。
df_counts = pd.concat([df['Brand'].str.count(x).rename(x) for x in word_list], axis=1)
看起来像:
loc top lot
0 1 0 0
1 0 1 0
2 1 0 1
3 0 0 1
4 1 0 0
5 0 0 0
1 - 存储出现次数的字典
df_counts.sum().to_dict()
[出局]
{'loc': 3, 'top': 1, 'lot': 2}
2 - 包含每行出现次数的新列
df['count'] = df_counts.sum(axis=1)
[出局]
Brand count
0 loc doc poc 1
1 roc top mop 1
2 loc lot not 2
3 roc lot tot 1
4 loc bot sot 1
5 nap rat sat 0
这是一种将计数转化为字典形式的方法:
df['Brand'].str.split(' ').explode().to_frame('Brand').groupby('Brand').size().loc[word_list].to_dict()
这是获取计数的方法:
df['count'] = df['Brand'].str.get_dummies(sep=' ').loc[:,word_list].sum(axis=1)