Python 在Pandas中计算字符串列中的单词数
我有一个pandas数据框,其中包含给定时间段内的查询和计数,我希望将此数据框转换为唯一单词的计数。例如,如果数据帧包含以下内容:Python 在Pandas中计算字符串列中的单词数,python,pandas,group-by,pandas-groupby,Python,Pandas,Group By,Pandas Groupby,我有一个pandas数据框,其中包含给定时间段内的查询和计数,我希望将此数据框转换为唯一单词的计数。例如,如果数据帧包含以下内容: query count foo bar 10 super 8 foo 4 super foo bar 2 我希望收到下面的数据帧。e、 g.“foo”一词在表格中正好出现16次 word count foo 16 bar 12 super 10 我正在使用下面的
query count
foo bar 10
super 8
foo 4
super foo bar 2
我希望收到下面的数据帧。e、 g.“foo”一词在表格中正好出现16次
word count
foo 16
bar 12
super 10
我正在使用下面的函数,但这似乎不是实现这一点的最佳方法,它忽略了每行的总计数
def _words(df):
return Counter(re.findall(r'\w+', ' '.join(df['query'])))
任何帮助都将不胜感激
提前谢谢 选项1
df['query'].str.get_dummies(sep=' ').T.dot(df['count'])
bar 12
foo 16
super 10
dtype: int64
选项2
df['query'].str.get_dummies(sep=' ').mul(df['count'], axis=0).sum()
bar 12
foo 16
super 10
dtype: int64
选项3
numpy.bincount
+pd.factorize
还强调了
cytoolz.mapcat
的使用。它返回一个迭代器,在该迭代器中映射函数并连接结果。太酷了
import pandas as pd, numpy as np, cytoolz
q = df['query'].values
c = df['count'].values
f, u = pd.factorize(list(cytoolz.mapcat(str.split, q.tolist())))
l = np.core.defchararray.count(q.astype(str), ' ') + 1
pd.Series(np.bincount(f, c.repeat(l)).astype(int), u)
foo 16
bar 12
super 10
dtype: int64
选项4
荒谬的东西使用。。。只需使用选项1
pd.DataFrame(dict(
query=' '.join(df['query']).split(),
count=df['count'].repeat(df['query'].str.count(' ') + 1)
)).groupby('query')['count'].sum()
query
bar 12
foo 16
super 10
Name: count, dtype: int64
另一种选择是使用
melt
+groupby
+sum
:
df['query'].str.split(expand=True).assign(count=df['count'])\
.melt('count').groupby('value')['count'].sum()
value
bar 12
foo 16
super 10
Name: count, dtype: int64