如何将 DataFrame 的字典更改为一个具有多列的 DataFrame

how to change dict of dataframes into one dataframe with multicolumns

提问人:f1msch 提问时间:5/31/2022 更新时间:5/31/2022 访问量:57

问:

因为我有几件物品,比如:

item = pd.DataFrame({'item1': np.random.randn(3),
                     'item2': np.random.randn(3)},
                    index=['a', 'b', 'c'])

然后将它们保存到一个字典中:

product = {'product1': item,
           'product2': item}

现在我想把这个字典改成一个数据帧,那么我认为多列的形式是一个更好的选择。 但是我怎么能把它变成这种结果呢?

             product1           product2
      item1     item2    item1     item2
a  2.517220 -0.391607 2.517220 -0.391607
b  0.546790  1.533278 0.546790  1.533278
c  1.187944  0.981451 1.187944  0.981451
Python 熊猫

评论


答:

4赞 ansev 5/31/2022 #1

使用 pd.concat

pd.concat({'product1': item,
           'product2': item}, axis=1)
#pd.concat(product, axis=1)