Converting pandas data to a list of tuples

I have sample data as shown below.

>>> df
   a  b
0  1  2
1  3  4

      

I want to convert this to a list of tuples. I tried to use itertuples()

for the same

>>> list(df.T.itertuples())
[('a', 1, 3), ('b', 2, 4)]

      

But I want the result to be in the format [('a', [1, 3]), ('b', [2, 4])] where the first value of the tuple is the column name and the second element in the tuple is a list column values.

I know it can be done by going through all the column names and manually creating a list of tuples. I'm just wondering if there is a smarter way to do this.

+3


source to share


1 answer


You can freeze column names with values โ€‹โ€‹as lists:



In [127]:
list(zip(df.columns,df.T.values.tolist()))

Out[127]:
[('a', [1, 3]), ('b', [2, 4])]

      

+7


source







All Articles