Lew*_*son 18 python group-by dataframe python-2.7 pandas
与PANDAS合作,尝试将数据框汇总为某些类别的计数,以及这些类别的均值情绪分数.
有完整的字符串表有不同的情绪分数,我想通过说出他们有多少帖子以及这些帖子的平均情绪来对每个文本来源进行分组.
我的(简化)数据框如下所示:
source text sent
--------------------------------
bar some string 0.13
foo alt string -0.8
bar another str 0.7
foo some text -0.2
foo more text -0.5
Run Code Online (Sandbox Code Playgroud)
这个输出应该是这样的:
source count mean_sent
-----------------------------
foo 3 -0.5
bar 2 0.415
Run Code Online (Sandbox Code Playgroud)
答案在某处:
df['sent'].groupby(df['source']).mean()
Run Code Online (Sandbox Code Playgroud)
然而,只给出每个来源,它的意思是,没有列标题.
提前致谢!
jez*_*ael 19
df = df.groupby('source') \
.agg({'text':'size', 'sent':'mean'}) \
.rename(columns={'text':'count','sent':'mean_sent'}) \
.reset_index()
print (df)
source count mean_sent
0 bar 2 0.415
1 foo 3 -0.500
Run Code Online (Sandbox Code Playgroud)
nev*_*ves 18
在较新版本的 Panda 中,您不再需要重命名,只需使用命名参数:
df = df.groupby('source') \
.agg(count=('text', 'size'), mean_sent=('sent', 'mean')) \
.reset_index()
print (df)
source count mean_sent
0 bar 2 0.415
1 foo 3 -0.500
Run Code Online (Sandbox Code Playgroud)
小智 6
下面一个应该可以正常工作:
df[['source','sent']].groupby('source').agg(['count','mean'])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13247 次 |
| 最近记录: |