Home > Enterprise >  How to connacenate dictionary of series
How to connacenate dictionary of series

Time:12-02

I have a dictionary of series

For example:

{'alpha': pd.Series(data=['a','b','c'], index=['A','B','C']),
 'beta': pd.Series(data=['d','e','f'], index=['B','C','D'])}

I want to transform it into a dataframe such that indexes compose columns, data compose rows and key is index.

index    A       B     C       D
alpha    a       b     c     NaN
beta             d     e      f

What is a good way of transforming this dictionary into this dataframe?

CodePudding user response:

One way:

entries = {'alpha':pd.Series(data=['a','b','c'],index=['A','B','C']),'beta':pd.Series(data=['d','e','f'],index=['B','C','D'])}
df = pd.DataFrame(entries).T

CodePudding user response:

You can use pd.DataFrame.from_dict:

>>> pd.DataFrame.from_dict(d, orient='index')
         A  B  C    D
alpha    a  b  c  NaN
beta   NaN  d  e    f

You can also use pd.concat and unstack

>>> pd.concat(d).unstack(level=1)
         A  B  C    D
alpha    a  b  c  NaN
beta   NaN  d  e    f
  • Related