70

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?

3

5 Answers 5

89

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
Sign up to request clarification or add additional context in comments.

4 Comments

If you haven't imported DataFrame separately you need to write it as : df = pd.DataFrame(series).transpose()
Done. The output is exactly what is desired.
MaxU's comment gave the best answer. series.to_frame().T
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.
38

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

1 Comment

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.
9

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

df = series.to_frame().reset_index()

Comments

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.

2 Comments

A little bit of an explanation as to how this works would be helpful. Remember than our answers are supposed to be instructive!
This doesn't produce the expected result.
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.