将列表解压缩到pandas中

时间:2015-03-18 20:49:45

标签: python pandas

鉴于我有一个列表,如何将其解压缩到pandas数据框中,如:

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

>> id  value1  value2
   01  Ad112   Ad113
   02          Ad213

1 个答案:

答案 0 :(得分:0)

您必须提取列名的各个元素,然后构建一个包含2行数据列表的列表:

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

一个动态方法是使用一个chunker(从这个question的一个答案中修改)来构建dict并用它来构造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