Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

python 2.7 - Pandas: A clean way to initialize data frame with a 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?

Many many thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...