[英]Pandas has two dataframes, want the average of the divisions between each group
[英]Want to group keys in a dictionary and then average each group
我想平均 csv 文件中一些视频游戏评论的情绪分数。 我为这些创建了一个字典,但想将 csv 中每一行的每个结果分组在一起。
blob = TextBlob(review_text)
for sentence in blob.sentences:
ssp = {"Game": index, "Polarity":sentence.sentiment.polarity}
print(ssp)
这给出了一个 output ,如下所示:
{'Game': 1, 'Polarity': -0.49687499999999996}
{'Game': 2, 'Polarity': 0.3865909090909091}
{'Game': 2, 'Polarity': 0.0}
{'Game': 2, 'Polarity': 0.2142857142857143}
{'Game': 2, 'Polarity': 0.2142857142857143}
{'Game': 2, 'Polarity': 0.04999999999999999}
{'Game': 2, 'Polarity': 0.0}
{'Game': 2, 'Polarity': -0.02500000000000005}
{'Game': 2, 'Polarity': 0.4715909090909091}
{'Game': 2, 'Polarity': 0.26666666666666666}
那么如何按第 1 场、第 2 场、第 3 场分组呢? 然后我想平均每个分数。
谢谢
您可以将字典放入列表中,然后对其进行分组/计算平均值:
from statistics import mean
# your code:
blob = TextBlob(review_text)
lst = []
for sentence in blob.sentences:
ssp = {"Game": index, "Polarity": sentence.sentiment.polarity}
lst.append(ssp)
# group it:
out = {}
for dct in lst:
out.setdefault(dct["Game"], []).append(dct["Polarity"])
# compute average:
for k, v in out.items():
print("Game:", k, "Average:", mean(v))
印刷:
Game: 1 Average: -0.49687499999999996
Game: 2 Average: 0.17537999037999039
另一种可能的解决方案,基于先前从dictionary
到pandas.DataFrame
的转换(将几个字典依次连接到数据帧中):
import pandas as pd
x = [{'Game': 1, 'Polarity': -0.49687499999999996},
{'Game': 2, 'Polarity': 0.3865909090909091},
{'Game': 2, 'Polarity': 0.0},
{'Game': 2, 'Polarity': 0.2142857142857143},
{'Game': 2, 'Polarity': 0.2142857142857143},
{'Game': 2, 'Polarity': 0.04999999999999999},
{'Game': 2, 'Polarity': 0.0},
{'Game': 2, 'Polarity': -0.02500000000000005},
{'Game': 2, 'Polarity': 0.4715909090909091},
{'Game': 2, 'Polarity': 0.26666666666666666}]
df = pd.DataFrame(dtype = 'object')
for y in x:
df = pd.concat([df, pd.DataFrame([y])], ignore_index = True)
df.groupby(['Game']).mean()
Output:
Polarity
Game
1 -0.496875
2 0.175380
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.