pandas将多个列(不存在)添加到dataframe行

时间:2017-07-27 17:21:49

标签: python pandas

使用此代码

a = pd.DataFrame([1,2,3])

如果我这样做

a.loc[0,'A']=3

我明白了:

   0   A
0  1   3
1  2 NaN
2  3 NaN

现在假设:

a = pd.DataFrame([1,2,3])
b=pd.DataFrame([[5,4],[6,3],[7,2]],columns=['B','C'])

有没有办法做[1,'A','B'] = b [2]得到的结果

   0   B   C
0  1 NaN NaN
1  2   7   2
2  3 NaN NaN

更新:我已经改变了一点问题,因为答案说明a和b有相同的索引,而不是。

3 个答案:

答案 0 :(得分:4)

您可以在join上使用a所需的b

In [150]: a.join(b.loc[0:0])
Out[150]:
   0    B    C
0  1  5.0  4.0
1  2  NaN  NaN
2  3  NaN  NaN

答案 1 :(得分:1)

一种可能性:

 public Details(String abc) {
    initComponents();
    jLabel5.setText(abc);
}

    //To change body of generated methods, choose Tools | Templates.

Details() {
     //To change body of generated methods, choose Tools | Templates.
}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { 
try{
  Class.forName("java.sql.Driver");
  Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost/foodframe", "root", "valli99");
  Statement stmt=(Statement) con.createStatement();
  String query="Update user set Name='"+jTextField1.getText()+"', Age='"+age+"', Restrictions='"+Restriction+"', Dislikes_Allergies='"+jTextArea1.getText()+"' where Username='"+jLabel5.getText()+"';";
  stmt.executeUpdate(query);

rs.close();
stmt.close();
con.close();
    }
 catch(Exception e){
 JOptionPane.showMessageDialog(null, e.getMessage());
}
}

给出import pandas as pd a = pd.DataFrame([1, 2, 3]) b = pd.DataFrame([[5, 4], [6, 3], [7, 2]], columns=['B', 'C']) a.loc[0, 'B'] = b.loc[0, 'B'] a.loc[0, 'C'] = b.loc[0, 'C']

a

答案 2 :(得分:1)

pd.concat

怎么样?
pd.concat([a,b.loc[b.index==0,:]],axis=1)

Out[53]: 
   0    B    C
0  1  5.0  4.0
1  2  NaN  NaN
2  3  NaN  NaN