0

I am trying to construct a Dataframe from lists, which have similar-size lists inside.

In the example below I have 3 lists (with similar-size lists inside), which I want to use to construct an specific Dataframe.

Here are the lists:

list_type = [['A1', 'A2'], ['A2'], ['A1', 'A3', 'A4']]

list_xx = [['1', '5'], ['3'], ['2', '7', '3']]

list_date = [['Jan', 'Jan'], ['Feb'], ['Mar', 'Mar', 'Mar']]

And the Dataframe I want to construct is:

   date type    xx
0   Jan   A1     1
1   Jan   A2     5
2   Feb   A2     3
3   Mar   A1     2
4   Mar   A3     7
5   Mar   A4     3

As you can see, the structure of the Dateframe is based on the inner-lists.

I would really value an efficient way of doing this in Python.

2 Answers 2

2

You can make do with concat and list comprehension:

pd.concat(pd.DataFrame({'date':d,'type':t,'xx':xx })
          for d,t,xx in zip(list_date, list_type, list_xx))

Or np.concatenate with transpose:

pd.DataFrame([np.concatenate(l) for l in (list_date,list_type,list_xx)],
             index=['date','type','xx']).T

Output:

  date type xx
0  Jan   A1  1
1  Jan   A2  5
0  Feb   A2  3
0  Mar   A1  2
1  Mar   A3  7
2  Mar   A4  3
Sign up to request clarification or add additional context in comments.

Comments

2

An alternative would be to flatten the lists first with itertools.chain.from_iterable, instead of concatenating DataFrames as in this answer.

import itertools
import pandas as pd

list_type = [['A1', 'A2'], ['A2'], ['A1', 'A3', 'A4']]
list_xx = [['1', '5'], ['3'], ['2', '7', '3']]
list_date = [['Jan', 'Jan'], ['Feb'], ['Mar', 'Mar', 'Mar']]

df = pd.DataFrame({
    "date": itertools.chain.from_iterable(list_date),
    "type": itertools.chain.from_iterable(list_type),
    "xx": itertools.chain.from_iterable(list_xx)
})

This gives your desired output. I would expect this to be more efficient than building and concatenating sub DataFrames, but haven't explicitly tested the two.

1 Comment

Excellent, please accept my answer if you end up going this route.

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.