Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫合并具有相同结构的两个数据帧_Python_Pandas_Dataframe - Fatal编程技术网

Python 熊猫合并具有相同结构的两个数据帧

Python 熊猫合并具有相同结构的两个数据帧,python,pandas,dataframe,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,

假设我有两个数据帧:

    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]   
一个(多个)可能的解决方案:

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]
一个(多个)可能的解决方案:

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]

使用
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]

使用
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]

谢谢你的回复。它能处理
int
float
类型吗?@natsuapo,我已经更新了我的答案-它会生成字符串列表谢谢你的回复。它可以处理
int
float
类型吗?@natsuapo,我已经更新了我的答案-它将生成stringsThanks列表,这似乎更灵活,可以应用于
reduce
。谢谢,这似乎更灵活,可以应用于
reduce