0

I have a simple Pandas data frame (df), structured like this:

   a   b   c   d
0  WW  XX  YY  ZZ
1  AA  BB  CC  DD
2  EE  FF  GG  HH
3       ...

I'd like to get this into a nested tuple structure inside of a list that looks like this:

[ ((WW, XX), YY, ZZ), ((AA, BB), CC, DD), ((EE, FF), GG, HH) ... ]

I'm just starting Python/Pandas, so I'm not really sure how to go about this.

2
  • this works for your dataset but is this really your dataset though as it's not dynamic: [((l[0], l[1]), l[2], l[3]) for l in df.values.tolist()] Commented Jan 9, 2015 at 14:30
  • Yeah, that's the format of the dataset at least. The actual values are larger than what I said here, but the format is the same. Thanks! Commented Jan 9, 2015 at 14:37

1 Answer 1

3

If you have a dataframe like this:

>>> df
   a  b  c
0  1  2  3
1  4  5  6
2  6  7  8

You can get the raw values into a list form like this:

>>> t = df.values.tolist()
>>> t
[[1, 2, 3], [4, 5, 6], [6, 7, 8]]

from there you can transform it into your tuples like so:

>>> tt= tuple(((a,b), c) for a,b,c in t)
>>> tt
(((1, 2), 3), ((4, 5), 6), ((6, 7), 8))
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.