Steve
Steve

Reputation: 505

Extracting a nested tuples from list (Python)

I have a list that has nested tuples.

nested = [['53062423-690f-4923-8f65-db710c038566', [('12253996-b2f7-46c7-b49f-09ca87cac84f', 'AFC_PoCv1.0'), ('b17bd025-611f-4728-9396-e59388ee59f6', 'Customer Profitability Sample'), ('b4a5d199-2c6f-4f8d-9fcb-5e4971254f73', 'Jammers vs Floaty Pants')]], ['988f64ea-14b2-4ad7-a899-ae40974c9139', [('9137e0f9-4063-479a-baff-8566c91302ff', 'DailySalesDashboard13Azure')]]]

I want to flatten the list into a pandas dataframe.

df = pd.DataFrame(nested, columns =('id', 'This column of tuples needs to split into two'))
df

results in,

enter image description here

but doesn't split the tuples into two columns with one tuple per row (with the associated id as the 3rd column). Feels like a simple list comprehension- but I have come up blank. Any help would be greatly appreciated.

Upvotes: 1

Views: 203

Answers (1)

BENY
BENY

Reputation: 323226

We do explode

s = pd.DataFrame(nested,columns=['c1','c2']).explode('c2').reset_index(drop=True)
# if only need to split the tuple , you do not need to do the next steps 

Split the tuple into single columns

s = s.join(pd.DataFrame(s['c2'].tolist()))
s
Out[162]: 
                                     c1  ...                              1
0  53062423-690f-4923-8f65-db710c038566  ...                    AFC_PoCv1.0
1  53062423-690f-4923-8f65-db710c038566  ...  Customer Profitability Sample
2  53062423-690f-4923-8f65-db710c038566  ...        Jammers vs Floaty Pants
3  988f64ea-14b2-4ad7-a899-ae40974c9139  ...     DailySalesDashboard13Azure
[4 rows x 4 columns]

Upvotes: 2

Related Questions