21

I have a list having Pandas Series objects, which I've created by doing something like this:

li = []
li.append(input_df.iloc[0])
li.append(input_df.iloc[4])

where input_df is a Pandas Dataframe

I want to convert this list of Series objects back to Pandas Dataframe object, and was wondering if there is some easy way to do it

Saurabh Verma
  • 6,328
  • 12
  • 52
  • 84

5 Answers5

30

Based on the post you can do this by doing:

pd.DataFrame(li)

To everyone suggesting pd.concat, this is not a Series anymore. They are adding values to a list and the data type for li is a list. So to convert the list to dataframe then they should use pd.Dataframe(<list name>).

Nicolaskn
  • 474
  • 3
  • 12
16

Since the right answer has got hidden in the comments, I thought it would be better to mention it as an answer:

pd.concat(li, axis=1).T

will convert the list li of Series to DataFrame

amonk
  • 1,769
  • 2
  • 18
  • 27
Saurabh Verma
  • 6,328
  • 12
  • 52
  • 84
2

It seems that you wish to perform a customized melting of your dataframe. Using the pandas library, you can do it with one line of code. I am creating below the example to replicate your problem:

import pandas as pd
input_df = pd.DataFrame(data={'1': [1,2,3,4,5]
                          ,'2': [1,2,3,4,5]
                          ,'3': [1,2,3,4,5]
                          ,'4': [1,2,3,4,5]
                          ,'5': [1,2,3,4,5]})

Using pd.DataFrame, you will be able to create your new dataframe that melts your two selected lists:

li = []
li.append(input_df.iloc[0])
li.append(input_df.iloc[4])
new_df = pd.DataFrame(li)

if what you want is that those two lists present themselves under one column, I would not pass them as list to pass those list back to dataframe. Instead, you can just append those two columns disregarding the column names of each of those columns.

new_df = input_df.iloc[0].append(input_df.iloc[4])

Let me know if this answers your question.

RenauV
  • 363
  • 2
  • 11
2

The answer already mentioned, but i would like to share my version:

li_df = pd.DataFrame(li).T
user1120
  • 109
  • 1
  • 1
  • 7
0

If you want each Series to be a row of the dataframe, you should not use concat() followed by T(), unless all your values are of the same datatype.

If your data has both numerical and string values, then the transpose() function will mangle the dtypes, likely turning them all to objects.

The right way to do this in general is:

  • Convert each series to a dict()
  • Pass the list of dicts either into the pd.Dataframe() constructor directly or use pd.Dataframe.from_dicts and set the orient keyword to "index."

In your case the following should work:

my_list_of_dicts = [s.to_dict() for s in li]
my_df = pd.Dataframe(my_list_of_dicts)
David R
  • 994
  • 1
  • 11
  • 27