我有一个新闻数据框,其中有一个专栏,其中包含全年撰写的所有文章的标题;另一列包含文章的月份;以及一个将文章分类为正面、负面、平衡或信息性的专栏。
数据框如下所示(此处仅包含一月和三月的虚构示例):
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/