[英]Pandas Count Positive/Negative/Neutral Values
In Python Pandas, I have a data frame with columns and records in the following format: 在Python Pandas中,我有一个数据框,其中包含以下格式的列和记录:
text source senti
-------------------------------
great food site1 0.6
awful staff site4 -0.4
good chef site8 0.4
average food site6 0.05
bad food site2 -0.8
The text column is essentially a description or opinion of something. 文本列实质上是对某事物的描述或看法。 I want to draw some conclusions about average sentiment on the sets of data, with the output like this.
我想得出一些关于数据集中的平均情绪的结论,其输出是这样的。
sentiment count
----------------
positive 2
neutral 1
negative 2
Where we have a count of 'senti' grouped as positive, negative or neutral. 在这里我们将“ senti”的数量分为积极,消极或中立。
The sentiments are counted as each group upon meeting the following conditions: 满足以下条件时,将情感计为每个组:
Big thanks in advance 提前谢谢
I'd use pd.cut
+ groupby
我会用
pd.cut
+ groupby
cut = pd.cut(
df.senti,
[-np.inf, -.1, .1, np.inf],
labels=['positive', 'neutral', 'negative']
)
df.groupby(cut).senti.count().reset_index(name='count')
senti count
0 positive 2
1 neutral 1
2 negative 2
As pointed out by @root, pd.value_counts
gives the same solution on the cut
variable. 正如@root指出的那样,
pd.value_counts
对cut
变量提供了相同的解决方案。
pd.value_counts(cut, sort=False).rename_axis('senti').reset_index(name='count')
使用的另一个版本apply
于映射到组:
df.groupby(df['senti'].apply(lambda x: 'negative' if x < -0.1 else 'positive' if x > 0.1 else 'neutral'))['senti'].count()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.