熊猫数据框:绘制有意义的图

时间:2015-04-21 19:56:54

标签: python dataframe python-ggplot

我有以下结果集但是绘制它因为它没有给出有意义的绘图,因为对于每个召回值,有多个精度值。如果我按原样绘制结果:

plot4 = ggplot(aes(x='recall', y='precision'), data=df_unique) + geom_line() + geom_point() + ggtitle("MoLT Evaluation test")
ggsave(plot4, "myplot.png")

与我们为此类指标获得的正常曲线相比,它给出了一个不那么漂亮的情节。

       precision    recall
1       0.000000  0.000000
17859   0.133333  0.009050
13159   0.066667  0.012195
9232    0.133333  0.012500
6131    0.066667  0.013333
7900    0.066667  0.014085
11671   0.066667  0.014925
5297    0.466667  0.015284
535     0.066667  0.015625
11223   0.133333  0.018018
5409    0.066667  0.019608
10840   0.266667  0.019802
13241   0.066667  0.020408
15957   0.200000  0.020833
21584   0.200000  0.021583
11746   0.333333  0.021834
11272   0.066667  0.022222
10904   0.066667  0.023256
13015   0.466667  0.023891
1010    0.533333  0.025641
2461    0.066667  0.027027
15294   0.200000  0.027523
11566   0.600000  0.028846
5103    0.066667  0.029412
7547    0.333333  0.030864
10059   0.333333  0.032258
20019   0.266667  0.033058
637     0.066667  0.033333
16226   0.200000  0.033708
9071    0.200000  0.034884

我想取每个值的平均值并构建一个新的数据框。

(Pdb) x[(x.recall == 0.1)]
       precision  recall
230     0.066667     0.1
119     0.133333     0.1
714     0.200000     0.1
284     0.266667     0.1
15705   0.333333     0.1
8057    0.466667     0.1
4871    0.533333     0.1

我想按如下方式构建我的新数据框

       precision  recall
   1     0.000     0.0
   2     0.104     0.1
   3     0.234     0.2

如何在应用模式下执行此类操作:

x[(x.recall == 0.1)]

或建立数据框的任何其他技术,每个唯一的召回值具有平均值。

1 个答案:

答案 0 :(得分:2)

将此问题分为两部分:

  • 创建一个' bin'
  • 上的分组列
  • 按新列分组数据,然后计算每组的平均值

您的代码可能如下所示:

import pandas as pd
import numpy as np

# ... load your data ...

# Create bins by rounding 'recall' to specified number of decimal places
df_unique["recall_bins"] = np.round(df_unique["recall"], 2)   

# Group your data according to the bins you just created
groups = df_unique.groupby("recall_bins")

# Calculate the means of each group
precision_means = groups.aggregate({"precision": np.mean})

您可以阅读有关split-apply-combine appraoch here的更多信息。