【问题标题】:Python - Counting Unique Labels in a Date RangePython - 计算日期范围内的唯一标签
【发布时间】:2018-03-13 12:06:40
【问题描述】:

我正在尝试对从互联网上抓取的一堆文本数据进行情绪分析。我已经到了我的 Pandas DataFrame 有我希望分析以下列的地步:“post_date”(格式为 dd-mm-yyyy,即 01-10-2017)和“Sentiment”(格式为“positive”, “中性”或“否定”)。

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

例如那些由以下公司生产的产品:

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

其中 date 是信息的分组方式(日、月、年等),而 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

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

【问题讨论】:

  • 你能添加数据样本和所需的输出吗?
  • @jezrael 我已经更新了帖子,希望有意义

标签: python pandas pandas-groupby


【解决方案1】:

你可以使用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

对于来自index的列:

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

【讨论】:

  • 非常感谢,效果很好!是否也可以按发布日期排序?目前它显示所有 01 例如:情绪负面_帖子中性_帖子正面_帖子总计_帖子帖子_日期 01-01-2014 0 0 3 3 01-01-2015 1 1 0 2
  • 我认为最好是在df['post_date'] = pd.to_datetime(df['post_date'])设置为日期时间之前
  • 只有我必须做的更改才被添加到 .to_datetime 中(dayfirst=True)
猜你喜欢
  • 2019-12-04
  • 1970-01-01
  • 2010-09-19
  • 2011-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多