Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: create dataframe from list of namedtuple

I'm new to pandas, therefore perhaps I'm asking a very stupid question. Normally initialization of data frame in pandas would be column-wise, where I put in dict with key of column names and values of list-like object with same length.

But I would love to initialize row-wise without dynamically concat-ing rows. Say I have a list of namedtuple, is there a optimized operation that will give me a pandas data frame directly from it?

like image 281
Patrick the Cat Avatar asked Nov 15 '13 23:11

Patrick the Cat


People also ask

How do you convert a list of tuples to a Pandas DataFrame?

To convert a Python tuple to DataFrame, use the pd. DataFrame() constructor that accepts a tuple as an argument and it returns a DataFrame.

How do you add a list to a DataFrame?

Using loc[] to Append The New List to a DataFrame. By using df. loc[index]=list you can append a list as a row to the DataFrame at a specified Index, In order to add at the end get the index of the last record using len(df) function.


1 Answers

In a similar vein to creating a Series from a namedtuple, you can use the _fields attribute:

In [11]: Point = namedtuple('Point', ['x', 'y'])  In [12]: points = [Point(1, 2), Point(3, 4)]  In [13]: pd.DataFrame(points, columns=Point._fields) Out[13]:     x  y 0  1  2 1  3  4 

Assuming they are all of the same type, in this example all Points.

like image 173
Andy Hayden Avatar answered Sep 18 '22 02:09

Andy Hayden