简体   繁体   English

Python列表到dataframe - AssertionError

[英]Python list of lists to dataframe - AssertionError

I have a list of lists in python. 我在python中有一个列表列表。 I am trying to convert it into a dataframe. 我试图将其转换为数据帧。 For eg = 例如=

foo = [
    [1,2,3...],
    [a,b,c...],
    [aa,bb,cc...]
]

Each of these 3 lists have 100 elements in them. 这3个列表中的每一个都包含100个元素。 I have tried the following to convert to a dataframe - 我尝试了以下转换为数据帧 -

df = pandas.DataFrame(foo, columns=headers)  // where headers is ['id', 'fname', 'lname']
df = pandas.DataFrame(foo, columns=[foo[0], foo[1], foo[2]])

However I am getting this error - 但是我收到这个错误 -

AssertionError: 3 columns passed, passed data had 100 columns

You can try the following methods. 您可以尝试以下方法。 The error comes from the fact that each sublist is interpreted as a row when using pandas.DataFrame constructor. 该错误来自于使用pandas.DataFrame构造函数时每个子列表被解释为一行的事实。 You can either make a dictionary out of the headers and the list: 您可以从标题和列表中创建字典:

import pandas as pd
headers = ['id', 'fname', 'name']
df = pd.DataFrame(dict(zip(headers, foo)))

df
#fname  id  lname
#0   a   1     aa
#1   b   2     bb
#2   c   3     cc
#3   d   4     dd
#4   e   5     ee

Or transpose the list: 或转置列表:

df = pd.DataFrame(list(zip(*foo)), columns=headers)

df
#  id   fname   lname
#0  1       a      aa
#1  2       b      bb
#2  3       c      cc
#3  4       d      dd
#4  5       e      ee

You can also try DataFrame.from_records transposing the Dataframe: 您还可以尝试DataFrame.from_records转置Dataframe:

In [17]: df = pd.DataFrame.from_records(foo).T

In [18]: df
Out[18]: 
   0  1   2
0  1  a  aa
1  2  b  bb
2  3  c  cc

In [19]: df.columns = ['id', 'fname', 'lname']

In [20]: df
Out[20]: 
  id fname lname
0  1     a    aa
1  2     b    bb
2  3     c    cc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM