Python pandas / numpy将1填充到具有值的单元格,将零填充为nan的单元格

时间:2017-11-12 17:17:46

标签: python arrays pandas numpy dataframe

我有一个包含不同类型数据(String,float,Integer,...)的单元格的数组。

e.g。

public class windowBuild extends JFrame {

    private static final long serialVersionUID = 1L;

    public windowBuild() {
        myPanel panel = new myPanel();
        panel.setBackground(Color.GRAY);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLayout(new BorderLayout());
        this.setSize(500, 500);
        this.setVisible(true);

        JPanel container = new JPanel();
        JPanel panelOne = new JPanel();
        JPanel panelTwo = new JPanel();

        panelTwo.add(new JLabel("2"));

        container.setLayout(new GridLayout(1, 2));
        container.add(panel);
        container.add(panelTwo);

        this.add(container);
    }

    class myPanel extends JPanel {
        public void paint(Graphics g) {
            g.setColor(Color.red);
            g.fill3DRect(10, 10, 10, 10, true);
        }
    }

    public static void main(String[] args) {
        new windowBuild();
    }
}

我想将0分配给值为[[18 '1/4/11' 73.0 'Male' 4.0] [18 nan 73.0 'Male' nan] [18 '7/5/11' 73.0 'Male' 7.0]] 的单元格,将1分配给所有其他单元格

预期结果:

nan

使用pandas的[[1 1 1 1 1 1 0 1 1 0 1 1 1 1 1]] ,我可以用{0}填充fillna(0),但是如果数据属于不同类型,如何为所有具有可用值的单元格分配1?

2 个答案:

答案 0 :(得分:1)

无论是数据框还是数组,都可以使用>>> arr = np.array([[18, '1/4/11', 73.0, 'Male', 4.0], ... [18, np.nan, 73.0, 'Male', np.nan], ... [18, '7/5/11', 73.0, 'Male', 7.0]], dtype=object) >>> pd.notnull(arr) array([[ True, True, True, True, True], [ True, False, True, True, False], [ True, True, True, True, True]], dtype=bool)

predict_proba(X[, check_input])

答案 1 :(得分:0)

创建布尔掩码并强制转换为整数:

~(np.isnan(arr)).astype(int)

或者:

 pd.notnull(arr).astype(int)