pandas Series to Dataframe using Series indexes as columns

PythonPandas

Python Problem Overview


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,

	0
a	1
b	2
c	3

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

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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

pd.DataFrame([series])

   a  b  c
0  1  2  3

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

series.to_frame().T
    
   a  b  c
0  1  2  3

Solution 3 - Python

you can also try this:

a = pd.Series.to_frame(series)

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

Explanation:
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.

Solution 4 - Python

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

df = series.to_frame().reset_index()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJzouView Question on Stackoverflow
Solution 1 - PythonPJayView Answer on Stackoverflow
Solution 2 - Pythoncs95View Answer on Stackoverflow
Solution 3 - PythonAmir RezaeiView Answer on Stackoverflow
Solution 4 - PythonPritesh ShrivastavaView Answer on Stackoverflow