Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Construct a pandas dataframe from a list of nested tuples

I have a list of tuples that looks like:

data = [('x', [('a', 1), ('b', 2), ('c', 3)]),
        ('y', [('d', 4), ('e', 5), ('f', 6)])]

I want to build a dataframe that looks like the one below from it:

A  B  C
x  a  1
x  b  2
x  c  3
y  d  4
y  e  5
y  f  6

I looked at this post and this post
but they don’t produce what I want.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can construct a list of tuples(with the rows) and pass it to pd.DataFrame class (with columns argument as ["A", "B", "C"])

>>> data = [
...     ("x", [("a", 1), ("b", 2), ("c", 3)]),
...     ("y", [("d", 4), ("e", 5), ("f", 6)]),
... ]
>>>
>>> import pandas as pd
>>>
>>> df = pd.DataFrame(
...     [(i, *k) for i, j in data for k in j],
...     columns=["A", "B", "C"],
... )
>>> print(df)
   A  B  C
0  x  a  1
1  x  b  2
2  x  c  3
3  y  d  4
4  y  e  5
5  y  f  6
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading