python - 对 Pandas 数据帧进行计数、平均和连接

标签 python pandas dataframe aggregate

我在 Pandas 中有一个数据框,其中包含一组产品评论,针对精选评论网站中略有不同的产品。每条评论都与一个产品相关,并带有数字分数。评论还有一个文本字段,其中包含每个评论的文本(相当长的字段)以及其来源站点的名称。 例如

product    score    source    text
------------------------------------------
K3         4.0      site1     long-text
P2         2.0      site7     text
K3         3.0      site2     paragraph
i7         1.0      site4     review-text
P2         5.0      site2     more-text
K3         4.0      site5     texts-on-text

我想将每个产品分组到一个新表中,以便我可以分析每个产品的审核情况。我最终将执行文本分析(POS 标记等)以了解每个产品的评论情况。

我想首先创建一个新的数据框,按“产品”分组。我想计算“计数”列中每个产品的评论数量。会有一列计算分组时“分数”的平均值。还有一个栏目将每个产品的文本字段组合在一起,以便可以将评论文本作为一个整体进行分析,而不是单独分析。 例如

product    mean_score    count     text_combined
---------------------------------------------------
K3         3.66          3         long-text, paragraph, texts-on-text
P2         3.5           2         text, more-text
i7         1.0           1         review-text

在此特定分析中不需要“源”列,但我将其包含在内只是为了表明数据框中还有其他列。

由此,我可以更轻松地分解每个产品的文本,而不是单独的评论。

提前感谢堆栈!

最佳答案

您可以使用groupbyagg :

df = df.groupby('product').agg({'score':'mean', 'source':'size', 'text': ', '.join})
#change order of columns, create column from index values 
df = df.reindex_axis(['score','source','text'], axis=1).reset_index()
#set new column names
df.columns = ['product','mean_score','count','text_combined']
print (df)
  product  mean_score  count                        text_combined
0      K3    3.666667      3  long-text, paragraph, texts-on-text
1      P2    3.500000      2                      text, more-text
2      i7    1.000000      1                          review-text

编辑:

输出中带有 dict 的解决方案:

from collections import Counter

df = df.groupby('product')
       .agg({'score':'mean', 'product':'size', 'text': ', '.join, 'source': lambda x: [dict(Counter(x))]})
#change order of columns, create column from index values 
df = df.reindex_axis(['score','product','text', 'source'], axis=1)
       .rename_axis('a')
       .reset_index()
#set new column names
df.columns = ['product','mean_score','count','text_combined', 'count_sources']
df['L'] = pd.Series(df.values.tolist())
print (df)
  product  mean_score  count                        text_combined  \
0      K3    3.666667      3  long-text, paragraph, texts-on-text   
1      P2    3.500000      2                      text, more-text   
2      i7    1.000000      1                          review-text   

                            count_sources  \
0  [{'site1': 1, 'site2': 1, 'site5': 1}]   
1              [{'site7': 1, 'site2': 1}]   
2                          [{'site4': 1}]   

                                                   L  
0  [K3, 3.6666666666666665, 3, long-text, paragra...  
1  [P2, 3.5, 2, text, more-text, [{'site7': 1, 's...  
2          [i7, 1.0, 1, review-text, [{'site4': 1}]]  

输出中带有元组的解决方案:

from collections import Counter

df = df.groupby('product')
       .agg({'score':'mean', 'product':'size', 'text': ', '.join, 'source': lambda x: list(dict(Counter(x)).items())})
#change order of columns, create column from index values 
df = df.reindex_axis(['score','product','text', 'source'], axis=1)
       .rename_axis('a')
       .reset_index()

#set new column names
df.columns = ['product','mean_score','count','text_combined', 'count_sources']
df['L'] = pd.Series(df.values.tolist())
print (df)
  product  mean_score  count                        text_combined  \
0      K3    3.666667      3  long-text, paragraph, texts-on-text   
1      P2    3.500000      2                      text, more-text   
2      i7    1.000000      1                          review-text   

                          count_sources  \
0  [(site1, 1), (site2, 1), (site5, 1)]   
1              [(site7, 1), (site2, 1)]   
2                          [(site4, 1)]   

                                                   L  
0  [K3, 3.6666666666666665, 3, long-text, paragra...  
1  [P2, 3.5, 2, text, more-text, [(site7, 1), (si...  
2            [i7, 1.0, 1, review-text, [(site4, 1)]]  

关于python - 对 Pandas 数据帧进行计数、平均和连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42694859/

相关文章:

python - YouTube-API上针对关键字/标签的无效字符错误(没有无效字符时)

Python - 尝试存储列表数组时陷入循环

python - 三次样条插值仅产生 nans 或引发错误

python - 有没有人有 Scrapy 中 sqlite 管道的示例代码?

python - 何时使用 * 和 ** 作为 python 函数中的函数参数

python - 分布式处理 - AWS Sagemaker

python - 使用 pandas to_gbq 读取数据在 Google BigQuery 中创建表时出现 400 错误

pandas - 根据另一个数据框 python pandas 替换列值? (初学者)

Python Pandas : How can I count the number of times a value appears in a column based upon another column?

python - 计算 Pandas 数据框中 np.nan 的数量