pandas Series to Dataframe using Series indexes as columns

Each Answer to this Q is separated by one/two green lines.

I have a Series, like this:

series = pd.Series({'a': 1, 'b': 2, 'c': 3})

I want to convert it to a dataframe like this:

    a   b   c
0   1   2   3

pd.Series.to_frame() doesn’t work, it got result like,

a   1
b   2
c   3

How can I construct a DataFrame from Series, with index of Series as columns?

You can also try this :

df = DataFrame(series).transpose()

Using the transpose() function you can interchange the indices and the columns.
The output looks like this :

    a   b   c
0   1   2   3

You don’t need the transposition step, just wrap your Series inside a list and pass it to the DataFrame constructor:


   a  b  c
0  1  2  3

Alternatively, call Series.to_frame, then transpose using the shortcut .T:


   a  b  c
0  1  2  3

you can also try this:

a = pd.Series.to_frame(series)

a['id'] = list(a.index)

The 1st line convert the series into a single-column DataFrame.
The 2nd line add an column to this DataFrame with the value same as the index.

Try reset_index. It will convert your index into a column in your dataframe.

df = series.to_frame().reset_index()

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .