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
To begin, here is the syntax that you may use to convert your Series to a DataFrame: df = my_series.to_frame () Alternatively, you can use this approach to convert your Series: df = pd.DataFrame (my_series)
Series can only contain single list with index, whereas dataframe can be made of more than one series or we can say that a dataframe is a collection of series that can be used to analyse the data. We are combining two series Author and Article published.
Create a dictionary so that we can combine the metadata for series. Metadata is the data of data that can define the series of values. Pass this dictionary to pandas DataFrame and finally you can see the result as combination of two series i.e for author and number of articles.
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>). Since the right answer has got hidden in the comments, I thought it would be better to mention it as an answer: This did not work for me.
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>)
.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With