如何在pandas数据框中按单词分组统计数据

4

我希望能够对Panda数据框按单词进行聚合。

基本上有3列与相应短语的点击/印象计数。我想将短语拆分为标记,然后将它们的点击次数相加,以决定哪个标记相对较好/较差。

期望的输入:如下所示的Panda数据框

   click_count  impression_count    text
1   10          100                 pizza
2   20          200                 pizza italian
3   1           1                   italian cheese

预期输出:
   click_count  impression_count  token
1   30         300                pizza      // 30 = 20 + 10, 300 = 200+100        
2   21         201                italian    // 21 = 20 + 1
3   1           1                 cheese     // cheese only appeared once in italian cheese
3个回答

1
tokens = df.text.str.split(expand=True)
token_cols = ['token_{}'.format(i) for i in range(tokens.shape[1])]
tokens.columns = token_cols

df1 = pd.concat([df.drop('text', axis=1), tokens], axis=1)
df1

enter image description here

df2 = pd.lreshape(df1, {'tokens': token_cols})
df2

enter image description here

df2.groupby('tokens').sum()

enter image description here


1
这将创建一个新的DataFrame,类似于piRSquared的DataFrame,但是令牌会堆叠并与原始数据合并:
(df['text'].str.split(expand=True).stack().reset_index(level=1, drop=True)
           .to_frame('token').merge(df, left_index=True, right_index=True)
           .groupby('token')['click_count', 'impression_count'].sum())
Out: 
         click_count  impression_count
token                                 
cheese             1                 1
italian           21               201
pizza             30               300

如果您将其分解,它会合并为以下内容:
df['text'].str.split(expand=True).stack().reset_index(level=1, drop=True).to_frame('token')
Out: 
     token
1    pizza
2    pizza
2  italian
3  italian
3   cheese

使用原始DataFrame的索引。得到的df为:

(df['text'].str.split(expand=True).stack().reset_index(level=1, drop=True)
           .to_frame('token').merge(df, left_index=True, right_index=True))
Out: 
     token  click_count  impression_count            text
1    pizza           10               100           pizza
2    pizza           20               200   pizza italian
2  italian           20               200   pizza italian
3  italian            1                 1  italian cheese
3   cheese            1                 1  italian cheese

剩下的是按照令牌列进行分组。

0

你可以这样做

In [3091]: s = df.text.str.split(expand=True).stack().reset_index(drop=True, level=-1)

In [3092]: df.loc[s.index].assign(token=s).groupby('token',sort=False,as_index=False).sum()
Out[3092]:
     token  click_count  impression_count
0    pizza           30               300
1  italian           21               201
2   cheese            1                 1

详情

In [3093]: df
Out[3093]:
   click_count  impression_count            text
1           10               100           pizza
2           20               200   pizza italian
3            1                 1  italian cheese

In [3094]: s
Out[3094]:
1      pizza
2      pizza
2    italian
3    italian
3     cheese
dtype: object

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接