Home > Mobile >  Construct a pandas dataframe from a list of nested tuples
Construct a pandas dataframe from a list of nested tuples

Time:05-05

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.

CodePudding user response:

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
  • Related