Search code examples
pandasdataframecreation

Create pandas dataframe by repeating one row with new multiindex


In Pandas I have a series and a multi-index:

s = pd.Series([1,2,3,4], index=['w', 'x', 'y', 'z'])
idx = pd.MultiIndex.from_product([['a', 'b'], ['c', 'd']])

What is the best way for me to create a DataFrame that has idx as index, and s as value for each row, preserving the index in S as columns?

df =
       w   x   y   z
a  c   1   2   3   4
   d   1   2   3   4
b  c   1   2   3   4
   d   1   2   3   4

Solution

  • Use the pd.DataFrame constructor followed by assign

    pd.DataFrame(index=idx).assign(**s)
    
         w  x  y  z
    a c  1  2  3  4
      d  1  2  3  4
    b c  1  2  3  4
      d  1  2  3  4