Pandas合并了两个具有相同结构的数据帧

时间:2017-07-14 10:41:31

标签: python pandas dataframe

假设我有两个数据帧:

    x1  x2  x3  
y1  a1  a1  a1      
y2  b1  b1  b1     
y3  c1  c1  c1  

    x1  x2  x3  
y1  a2  a2  a2      
y2  b2  b2  b2     
y3  c2  c2  c2         

使用每个元素获取以下数据帧的最简单方法是从原始数据帧中的同一位置获取两个值的列表?

    x1        x2       x3  
y1  [a1,a2]  [a1,a2]  [a1,a2]     
y2  [b1,b2]  [b1,b2]  [b1,b2]     
y3  [c1,c2]  [c1,c2]  [c1,c2]   

2 个答案:

答案 0 :(得分:4)

一个(众多)可能的解决方案:

In [63]: d1.astype(str).add(',').add(d2.astype(str)).apply(lambda x: x.str.split(','))
Out[63]:
          x1        x2        x3
y1  [a1, a2]  [a1, a2]  [a1, a2]
y2  [b1, b2]  [b1, b2]  [b1, b2]
y3  [c1, c2]  [c1, c2]  [c1, c2]

答案 1 :(得分:3)

使用applymap

In [953]: df1.applymap(lambda x: [x]) + df2.applymap(lambda x: [x])
Out[953]:
          x1        x2        x3
y1  [a1, a2]  [a1, a2]  [a1, a2]
y2  [b1, b2]  [b1, b2]  [b1, b2]
y3  [c1, c2]  [c1, c2]  [c1, c2]