0

I have a list as follows:

[[100,200,300],[10,20,30,40]]

I want to transform each element into a column of a pandas df

The end result looks like:

Col1   Col2    Col3    Col4
100    200     300
10     20      30       40

How can I achieve this? There is a max size of 4 items per list but could be lower.

1
  • 3
    im not sure if I miss something, but just simple df = pd.DataFrame(list_of_lists) works? Commented Apr 16, 2022 at 0:57

1 Answer 1

1
lst = [[100,200,300],[10,20,30,40]]
pd.DataFrame(lst).add_prefix("Col")
Sign up to request clarification or add additional context in comments.

4 Comments

What if (and I think thats also what the OP wants to know) the 4-column-df is the base. Our input list has a max size of 4 or less. Now if none of the list of lists have a length of 4 (1st list 3, 2nd list 3 elements) then I get an error when passing the data to the df ValueError: 4 columns passed, passed data had 3 columns .any idea how to fill that df except just fill it by looping ?
Use add_prefix
unfortunately not what i meant. DataFrame has to have always 4 columns. if you pass the list of lists into that df (saying one list has 3 elements, one has 2) then the last column of the df has 2 Nan but still there are 4 column there.
.reindex(columns=range(4))

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.