将行从一个Dataframe插入另一个Dataframe

时间:2017-08-29 14:43:26

标签: python pandas

是否有可能在指定位置将一行数据帧添加到另一个数据帧? 我试图修改this solution,但它无法正常工作。

如果我尝试以下操作,我的行总是以列的形式添加:

template<class argument1, class argument2, class result>  
class binary_function{  
    public:  
    typedef argument1 first_argument_type;  
    typedef argument2 second_argument_type;  
    typedef result result_type;  
};  
class cmplxData : binary_function<double, double, int>{  
    public:  
            result_type operator()(first_argument_type t1,    second_argument_type t2){  
                    return (result_type)(t1+t2);  
            }  
};

int main(int argc, char *argv[]){  
    return 0;  
}  

另外它们看起来像这样

df1 = pd.concat([df1[:2], df2[1], df1.iloc[2:]]).reset_index(drop=True)

print (df1)

     A    B    C    D    0
0    X    X    Y    Y  NaN
1   15   12    8    4  NaN
2  NaN  NaN  NaN  NaN   15
3  NaN  NaN  NaN  NaN   12
4  NaN  NaN  NaN  NaN    8
5  NaN  NaN  NaN  NaN    4
6   21   13    5    9  NaN

如上所述,我也尝试使用相同DataFrame中的行

1 个答案:

答案 0 :(得分:1)

IIUC:

df1 = pd.DataFrame({'Col1':['A']*5, 'Col2':['B']*5})

  Col1 Col2
0    A    B
1    A    B
2    A    B
3    A    B
4    A    B

df2 = pd.DataFrame(data=[['X','Z'],['W','U'],['T','S']],columns=['Col1','Col2'])

  Col1 Col2
0    X    Z
1    W    U
2    T    S

在df2索引行1中将行插入到索引行2和行3之间的df1中:

pd.concat([df1[:2],df2.loc[1,:].to_frame().T,df1[2:]],ignore_index=True)

输出:

  Col1 Col2
0    A    B
1    A    B
2    W    U
3    A    B
4    A    B
5    A    B
相关问题