使用从其他数据框创建的元组的每个元素创建pandas数据帧

时间:2017-01-28 10:23:45

标签: pandas dataframe tuples

我需要创建一个包含来自一系列数据帧阵列的元组的数据帧。我需要的是以下内容:

我有数据框ab

a = pd.DataFrame(np.array([[1, 2],[3, 4]]), columns=['one', 'two'])
b = pd.DataFrame(np.array([[5, 6],[7, 8]]), columns=['one', 'two'])

a:
   one  two
0    1    2
1    3    4

b: 
   one  two
0    5    6
1    7    8

我想创建一个数据帧a_b,其中每个元素都是由a和b中相应元素组成的元组,即

a_b = pd.DataFrame([[(1, 5), (2, 6)],[(3, 7), (4, 8)]], columns=['one', 'two'])

a_b: 
      one     two
0  (1, 5)  (2, 6)
1  (3, 7)  (4, 8)

理想情况下,我想用任意数量的数据帧来做这件事。 我希望有一种比使用for循环更优雅的方式 我正在使用python 3

2 个答案:

答案 0 :(得分:2)

您可以使用numpy.rec.fromarrays((a.values, b.values)).tolist()

In [34]: pd.DataFrame(np.rec.fromarrays((a.values, b.values)).tolist(), 
                      columns=a.columns,
                      index=a.index)
Out[34]:
      one     two
0  (1, 5)  (2, 6)
1  (3, 7)  (4, 8)

合并三个DF&#39>:

In [36]: pd.DataFrame(np.rec.fromarrays((a.values, b.values, a.values)).tolist(),
                      columns=a.columns,
                      index=a.index)
Out[36]:
         one        two
0  (1, 5, 1)  (2, 6, 2)
1  (3, 7, 3)  (4, 8, 4)

<强>更新

  

假设您事先并不知道数据帧的数量,会怎样   你呢?

In [60]: dfs = [a,b,a]

In [62]: tuple_of_dfs = (x.values for x in dfs)

In [63]: pd.DataFrame(np.rec.fromarrays(tuple_of_dfs).tolist(), columns=a.columns, index=a.index)
Out[63]:
         one        two
0  (1, 5, 1)  (2, 6, 2)
1  (3, 7, 3)  (4, 8, 4)

答案 1 :(得分:0)

您可以在zipa

的列上使用b
In [31]: pd.DataFrame({x: zip(a[x], b[x]) for x in a.columns})
Out[31]:
      one     two
0  (1, 5)  (2, 6)
1  (3, 7)  (4, 8)
相关问题