按组

时间:2017-07-26 20:07:26

标签: python pandas split-apply-combine

如果这是重复的道歉,我没有找到类似的答案。

大图:我有一个带有NaN值的df,我想用该列的推算中值替换。但是,我发现sklearn中的内置imputers使用了整个列的中位数(或任何指标)。我的数据有标签和我想用属于该标签的其他样本替换每个NaN值和该列的中值。

我可以通过将df分成每个标签的一个df,在每个dfs上进行输入和组合来实现这一点,但是这种逻辑不能很好地扩展。我最多可以上20节课,而且我从根本上不相信这是“正确”的方式。

我想通过在split-apply-combine技术(或您认为可行的其他技术)中使用groupby对象而不复制我的df来执行此操作。感谢您的帮助。

示例df:

   r1  r2   r3   label
0  12  NaN  58       0
1  34  52   24       1
2  32   4  NaN       1
3   7  89    2       0
4  22  19   12       1

在这里,我希望(0,r2)处的NaN值等于标签0的该列的中位数,即值89(从3,r2)。

我希望(2,r3)的NaN值等于标签1的该列的中位数,即中位数(24,12)或18。

示例成功结果:

   r1  r2   r3   label
0  12   89  58       0
1  34  52   24       1
2  32   4   18       1
3   7  89    2       0
4  22  19   12       1

1 个答案:

答案 0 :(得分:0)

public class Application : Gtk.Window {
    public Application () {
        // Prepare Gtk.Window:
        this.title = "My Gtk.TreeView";
        this.window_position = Gtk.WindowPosition.CENTER;
        this.destroy.connect (Gtk.main_quit);
        this.set_default_size (350, 70);

        Gtk.Box box = new Gtk.Box (Gtk.Orientation.VERTICAL, 6);

        // The Model:
        Gtk.ListStore list_store = new Gtk.ListStore (2, typeof (string), typeof (Gdk.RGBA));
        Gtk.TreeIter iter;

        list_store.append (out iter);
        list_store.set (iter, 0, "Stack", 1, "#FFFFFF");
        list_store.append (out iter);
        list_store.set (iter, 0, "Overflow", 1, "#FFFFFF");
        list_store.append (out iter);
        list_store.set (iter, 0, "Vala", 1, "#FFFFFF");
        list_store.append (out iter);
        list_store.set (iter, 0, "Gtk", 1, "#FFFFFF");

        // The View:
        Gtk.TreeView view = new Gtk.TreeView.with_model (list_store);
        box.add (view);

        Gtk.ToggleButton button = new Gtk.ToggleButton.with_label ("Change bg color row 3");
        box.add (button);

        this.add (box);

        Gtk.CellRendererText cell = new Gtk.CellRendererText ();
        view.insert_column_with_attributes (-1, "State", cell, "text", 0, "background-rgba", 1);


        // Setup callback to change bg color of row 3
        button.toggled.connect (() => {
            // Reuse the previous TreeIter
            list_store.get_iter_from_string (out iter, "2");

            if (!button.get_active ()) {
                list_store.set (iter, 1, "#c9c9c9");
            } else {
                list_store.set (iter, 1, "#ffffff");
            }
        });
    }

    public static int main (string[] args) {
        Gtk.init (ref args);

        Application app = new Application ();
        app.show_all ();
        Gtk.main ();
        return 0;
    }
}

或使用In [158]: df.groupby('label', group_keys=False) \ .apply(lambda x: x.fillna(x.median()).astype(int)) Out[158]: r1 r2 r3 label 0 12 89 58 0 3 7 89 2 0 1 34 52 24 1 2 32 4 18 1 4 22 19 12 1

transform
相关问题