ArchieTiger
ArchieTiger

Reputation: 2243

Unpack list into pandas

Given I have a list, how can I unpack it into a pandas data frame such as:

data = {u'2344': ["id", "value1", "value2", "01", "Addf112", "Addf113", "02", " ", "Addf213"]}

>> id  value1  value2
   01  Ad112   Ad113
   02          Ad213

Upvotes: 0

Views: 1164

Answers (1)

EdChum
EdChum

Reputation: 393973

You'd have to extract the individual elements for the column names and then construct a list consisting of 2 lists for your 2 rows of data:

In [23]:

data = {u'2344': ["id", "value1", "value2", "01", "Addf112", "Addf113", "02", " ", "Addf213"]}

pd.DataFrame(columns = data['2344'][:3], data=[data['2344'][3:6], data['2344'][6:]])
Out[23]:
   id   value1   value2
0  01  Addf112  Addf113
1  02           Addf213

A dynamic method would be to use a chunker (modified from one of the answers to this question) to build the dict and use this to construct the df:

In [59]:

def chunker(seq, stride):
    cols = seq[:stride]
    data = [seq[stride:][pos::stride] for pos in range(0, stride)]
    return dict(zip(cols,data))

pd.DataFrame(chunker(data['2344'],3))

Out[59]:
   id   value1   value2
0  01  Addf112  Addf113
1  02           Addf213

Upvotes: 1

Related Questions