user7864386
user7864386

Reputation:

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.

Upvotes: 1

Views: 441

Answers (1)

user459872
user459872

Reputation: 24592

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

Upvotes: 2

Related Questions