Rallad
Rallad

Reputation: 101

Conver a dataframe to a list of tuples

So I've been trying to convert a dataframe into a list, with the pandas package on python, with the format as such:

[('row1 element1', 'row1 element2', 'row1 element3'), ('row2 element1', 'row2 element2', 'row2 element3'), ('row3 element1', 'row3 element2', 'row3 element3')...]

The closest I've managed is using the following snippet:

df.values.tolist()

however this gives the following format:

['row1 element1', 'row1 element2', 'row1 element3'],
['row2 element1', 'row2 element2', 'row2 element3'],
['row3 element1', 'row3 element2', 'row3 element3']...

Is there any simply way to obtain the format needed? Perhaps an existing method or a simple iterative process could be suggested. Any help is appreciated.

Upvotes: 0

Views: 42

Answers (2)

yatu
yatu

Reputation: 88275

You can generate an array of records for a fast approach:

df.to_records(index=False).tolist()

Upvotes: 2

Etoneja
Etoneja

Reputation: 1083

If you want convert list of lists to list of tuples, so:

>>> a = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14], [15, 16, 17], [18, 19]]
>>> [tuple(x) for x in a]
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11), (12, 13, 14), (15, 16, 17), (18, 19)]

Upvotes: 1

Related Questions