62

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?

Jzou
  • 1,225
  • 3
  • 11
  • 22

5 Answers5

84

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
PJay
  • 2,557
  • 1
  • 14
  • 12
  • 6
    If you haven't imported DataFrame separately you need to write it as : `df = pd.DataFrame(series).transpose() ` – PJay Oct 24 '16 at 17:50
  • 2
    Done. The output is exactly what is desired. – PJay Oct 24 '16 at 17:57
  • 3
    MaxU's comment gave the best answer. series.to_frame().T – Jzou Oct 24 '16 at 17:59
  • 1
    Warning : this method works very well for small series, but if you use longer ones, the complexity exploses. For me, it ran for 21 seconds for a single series of 2755 columns. – Thomas Dussaut Jun 09 '17 at 07:30
35

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
cs95
  • 379,657
  • 97
  • 704
  • 746
  • `pd.DataFrame([series])` is better than `transpose`. You don't have to remember what goes to index at when, and then what gets moved to columns. – Steve Lihn Feb 02 '22 at 16:53
8

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.

Diansheng
  • 1,081
  • 12
  • 19
Amir Rezaei
  • 89
  • 1
  • 1
7

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

df = series.to_frame().reset_index()
2

This

pd.DataFrame([series]) #method 1

produces a slightly different result than

series.to_frame().T #method 2

With method 1, the elements in the resulted dataframe retain the same type. e.g. an int64 in series will be kept as an int64.

With method 2, the elements in the resulted dataframe become objects IF there is an object type element anywhere in the series. e.g. an int64 in series will be become an object type.

This difference may cause different behaviors in your subsequent operations depending on the version of pandas.

S. Wong
  • 59
  • 6