user818489
user818489

Reputation:

Convert pandas dataframe to list of tuples

I have a sample dataframe as follows

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

I want to convert this to a list of tuples. I tried using itertuples() for the same

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

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

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

Upvotes: 3

Views: 7870

Answers (1)

EdChum
EdChum

Reputation: 394459

You can zip the column names with the values as lists:

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

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

Upvotes: 7

Related Questions