首页 > 解决方案 > Getting ValueError: DataFrame constructor not properly called while creating a dataframe from lists of list

问题描述

I am getting below error while converting Lists of list to dataframe:

raise ValueError('DataFrame constructor not properly called!') ValueError: DataFrame constructor not properly called!

I have used numpy to split the list and now need to convert those lists of list to a dataframe:


    import numpy as np
    import pandas as pd

    def SplitList():
        l = np.array([6,2,5,1,3,6,9,7,6])
        n = 3

        list = l.reshape((len(l)//n), n).T
        print(list)

    df = pd.DataFrame(list)

标签: python-3.xpandasdataframetype-conversionnested-lists

解决方案


首先,不要list用作变量名,它是 Python 中的保留关键字。

其次,你需要你的函数到return你的重塑数组,所以你需要:

import numpy as np
import pandas as pd

def SplitList():
    l = np.array([6,2,5,1,3,6,9,7,6])
    n = 3

    a = l.reshape((len(l)//n), n).T
    return a

df = pd.DataFrame(SplitList())

print(df)

   0  1  2
0  6  1  9
1  2  3  7
2  5  6  6

只是一个建议,但可能是使您的功能更可重用的想法。例如:

def split_list(arr, n):
    arr = np.array(arr)
    return arr.reshape(-1, n).T

split_list([6,2,5,1,3,6,9,7,6], 3)

[出去]

[[6 1 9]
 [2 3 7]
 [5 6 6]]

推荐阅读