1

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.

1 Answer 1

2

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
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.