Python - 计算日期范围内的唯一标签

标签 python pandas pandas-groupby

我正在尝试对从互联网上抓取的一堆文本数据进行情感分析。我已经达到了这样的程度,我的 Pandas DataFrame 具有我希望分析的以下列:“post_date”(格式为 dd-mm-yyyy,即 01-10-2017)和“情绪”(格式为“积极”, “中性”或“负面”)。

我希望能够统计每天/每月/每年的帖子数量以及每天的正面/中立/负面帖子数量。

例如:

print pd.value_counts(df.Sentiment)

但是我被卡住了,我已经尝试了 groupby 命令的多次迭代(如下),但不断出现错误。

df.groupby(df.post_date.dt.year)

有人可以帮助我实现这一目标吗?

理想情况下,所需的输出类似于:

Date, Postive_Posts, Negative_Posts, Neutral_Posts, Total_Posts
01/10/2017, 10, 5, 8, 23
02/10/2017, 5, 20, 5, 30

其中,日期是信息的分组方式(日、月、年等),pos/neg/neu 列是与该范围内的标签计数相对应的帖子总数,最后,total_posts 是该范围内的帖子总数。

目前的数据是:

post_date, Sentiment
19/09/2017, positive
19/09/2017, positive
19/09/2017, positive
20/09/2017, negative
20/09/2017, neutral

如果您需要更多信息,请告诉我。

最佳答案

您可以使用groupby + size + unstack + add_suffix + sum :

df1 = df.groupby(['post_date','Sentiment']).size().unstack(fill_value=0).add_suffix('_Posts')
df1['Total_Posts'] = df1.sum(axis=1)
print (df1)

Sentiment   negative_Posts  neutral_Posts  positive_Posts  Total_Posts
post_date                                                             
19/09/2017               0              0               3            3
20/09/2017               1              1               0            2

一行解决方案非常相似 - 只需要 assign :

df1 = (df.groupby(['post_date','Sentiment'])
        .size()
        .unstack(fill_value=0)
        .add_suffix('_Posts')
        .assign(Total_Posts=lambda x: x.sum(axis=1)))

print (df1)

Sentiment   negative_Posts  neutral_Posts  positive_Posts  Total_Posts
post_date                                                             
19/09/2017               0              0               3            3
20/09/2017               1              1               0            2

对于索引中的列:

df1 = (df.groupby(['post_date','Sentiment'])
        .size()
        .unstack(fill_value=0)
        .add_suffix('_Posts')
        .assign(Total_Posts=lambda x: x.sum(axis=1))
        .reset_index()
        .rename_axis(None, axis=1))

print (df1)

    post_date  negative_Posts  neutral_Posts  positive_Posts  Total_Posts
0  19/09/2017               0              0               3            3
1  20/09/2017               1              1               0            2

关于Python - 计算日期范围内的唯一标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46525175/

相关文章:

python - OpenCV 无法从视频捕获设备读取

python - 百分比格式的 XlsxWriter 错误

python - 循环遍历 groupby 为 pandas 中的名称分配数字

python - 如何使用 Django 的内置框架为评论添加确认消息?

python - 在 Python 中循环压缩多个列表

python - 匹配并删除文件中的字符串

python - Pandas 将列从一个数据框复制到另一个具有不同名称的数据框

python - pandas 数据框的两列 - Python 中的 Concat

python - 查找特定列的平均值并保留具有特定平均值的所有行

Pandas 数据框 : extract data with specific crtieria/conditions minimum in a column fixing other columns