【问题标题】:Create pandas dataframe with each element a tuple created from other dataframes创建熊猫数据框,每个元素都是从其他数据框创建的元组
【发布时间】:2017-01-28 10:23:44
【问题描述】:

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

我有 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

【问题讨论】:

    标签: pandas dataframe tuples


    【解决方案1】:

    您可以在 ab 的列上使用 zip

    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)
    

    【讨论】:

      【解决方案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:

      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)
      

      【讨论】:

      • 谢谢,这个很好用,但是假设你事先不知道数据帧的数量,你会怎么做?
      • @gionni,请参阅更新部分
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-04
      • 1970-01-01
      • 2020-09-21
      • 2020-03-12
      • 2021-02-08
      • 2023-02-01
      • 2021-05-07
      相关资源
      最近更新 更多