1

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)

1 Answer 1

1

First of all, don't use list as a variable name, it is a reserved keyword in Python.

Secondly, you need your function to return your reshaped array, so you need:

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

Just a suggestion, but may be an idea to make your function more reusable. For example:

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)

[out]

[[6 1 9]
 [2 3 7]
 [5 6 6]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.