I have a python pandas dataframe df like this:
a b
1 3
3 6
5 7
6 4
7 8
I want to transfer it to a list:
[(1,3),(3,6),(5,7),(6,4),(7,8)]
Thanks.
I have a python pandas dataframe df like this:
a b
1 3
3 6
5 7
6 4
7 8
I want to transfer it to a list:
[(1,3),(3,6),(5,7),(6,4),(7,8)]
Thanks.
If performance is important, use a list comprehension:
[tuple(r) for r in df.to_numpy()]
# [(1, 3), (3, 6), (5, 7), (6, 4), (7, 8)]
Note: For pandas < 0.24, please use df.values
instead.
You may find even better performance if you iterate over lists instead of the numpy array:
[tuple(r) for r in df.to_numpy().tolist()]
# [(1, 3), (3, 6), (5, 7), (6, 4), (7, 8)]
This method to any number of columns. However, if you want to select a specific set of columns to convert, you can select them beforehand.
[tuple(r) for r in df[['a', 'b']].to_numpy()]
# [(1, 3), (3, 6), (5, 7), (6, 4), (7, 8)]
Another alternative is using map
.
list(map(tuple, df.to_numpy()))
# [(1, 3), (3, 6), (5, 7), (6, 4), (7, 8)]
This is roughly the same as the list comprehension, performance wise. You can generalise the same way.
Another option is to use apply
and convert the result to a list:
df.apply(tuple, axis=1).tolist()
# [(1, 3), (3, 6), (5, 7), (6, 4), (7, 8)]
This is slower, so it not recommended.
You can also get the desired list like that:
zip(list(df['a']), list(df['b']))
Use zip()
to create tuples
df = pd.DataFrame({'a':[1,3,5,6,7], 'b':[3,6,7,4,8]})
print(list(zip(df['a'], df['b']))