python - 如何创建一个列,其中包含满足特定条件的特定实例的计数?

标签 python pandas

我有一个新闻数据框,其中有一个专栏,其中包含全年撰写的所有文章的标题;另一列包含文章的月份;以及一个将文章分类为正面、负面、平衡或信息性的专栏。

数据框如下所示(此处仅包含一月和三月的虚构示例):

Headline                    month          tendency
'The US Economy xxxxxx'     January        positive
'The UN warns xxxxxxxx'     January        balanced
'Tesla xxxxxxxx'            March          positive

数据涵盖所有月份,我想创建一个名为 count 的列,其中包含特定月份中发表的文章数量,包括积极的、消极的、平衡的或信息性的。例如,假设一月份共有 40 篇文章,其中 20 篇是正面的,5 篇是平衡的,5 篇是信息性的,10 篇是负面的。 3 月份,您总共有 30 篇文章,其中 15 篇正面文章、5 篇负面文章、5 篇平衡文章和 5 篇信息性文章。在我想要创建的专栏中,根据文章的倾向,该值将是前面提到的数字。所以最终的数据框将如下所示:

Headline                    month          tendency     count
'The US Economy xxxxxx'     January        positive     20
'The UN warns xxxxxxxx'     January        balanced     5
'Tesla xxxxxx'              March          positive     15

count的值重复并不重要,我只是需要它作为引用。

我能够打印结果,并且逻辑运行得非常好,但我无法找到创建列并为每个月分配值的方法。

我的代码如下所示:

data[(data[month] == 'January') & (data['tendency'] == 'Positive')].count()

您可以更改月份和趋势,它将为您提供所需的结果。我应该为每个月和每个趋势写一个 if 语句吗?创建计数列的最佳方法是什么?

最佳答案

因此,您可以通过聚合/groupby 的组合来完成此操作和一个join

例如像这样的东西:

# This is input, named 'df', I added a fourth headline to test the aggregation.
df = pd.DataFrame({'Headline' : ['The US Economy xxxxxx','The UN warns xxxxxxxx','Tesla xxxxxxxx','Tesla yyyyyyy'],
                      'month' : ['January','January','March','March'],
                   'tendency' : ['positive', 'balanced', 'positive', 'positive']})

# Make a series that counts articles by month and tendency
countByMonthTendency = df.groupby(['month','tendency']).size().rename('count')

# Join it back to your data on the same two columns.
df.join(countByMonthTendency, on=['month','tendency'])

产生:

    Headline                month    tendency   count
0   The US Economy xxxxxx   January  positive   1
1   The UN warns xxxxxxxx   January  balanced   1
2   Tesla xxxxxxxx          March    positive   2
3   Tesla yyyyyyy           March    positive   2

关于python - 如何创建一个列,其中包含满足特定条件的特定实例的计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55680433/

相关文章:

python - 报告两个相同形状的数据帧之间的差异/值变化

python - Python中 block 的概念

python替代解决方案scipy空间距离,当前解决方案返回MemoryError

python - 如果 A 列中的单元格为空,则修改 B 列中的单元格

python - 通过列中的标签列表对 Pandas 数据框行进行分组的有效方法

python - 根据其他数据帧从数据帧中选择值

python - python.subprocess(cppBinaryExe) 会影响 cppBinaryExe 的性能吗?

python - 如何将 YouTube API 持续时间转换为秒数?

python - 对两列进行分组并计算第三列中的唯一值

python - 加快 Pandas 中 csv 文件的条件行读取速度?