问题描述
我有一个像这样的python pandas dataframe df:
I have a python pandas dataframe df like this:
a b
1 3
3 6
5 7
6 4
7 8
我想将其转移到列表中
[(1,3),(3,6),(5,7),(6,4),(7,8)]
谢谢.
推荐答案
如果性能很重要,请使用列表理解:
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)]
注意:对于熊猫< 0.24,请改用df.values
.
Note: For pandas < 0.24, please use df.values
instead.
如果遍历列表而不是numpy数组,则可能会发现更好的性能:
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)]
另一种替代方法是使用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.
另一种选择是使用apply
并将结果转换为列表:
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.
这篇关于将数据框转换为元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!