pandas 将数据帧转换为元组数组 [英] Pandas convert dataframe to array of tuples

查看:32
本文介绍了 pandas 将数据帧转换为元组数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用 Pandas 处理了一些数据,现在我想批量保存回数据库.这需要我将数据帧转换为元组数组,每个元组对应于数据帧的行".

I have manipulated some data using pandas and now I want to carry out a batch save back to the database. This requires me to convert the dataframe into an array of tuples, with each tuple corresponding to a "row" of the dataframe.

我的 DataFrame 看起来像:

My DataFrame looks something like:

In [182]: data_set
Out[182]: 
  index data_date   data_1  data_2
0  14303 2012-02-17  24.75   25.03 
1  12009 2012-02-16  25.00   25.07 
2  11830 2012-02-15  24.99   25.15 
3  6274  2012-02-14  24.68   25.05 
4  2302  2012-02-13  24.62   24.77 
5  14085 2012-02-10  24.38   24.61 

我想将其转换为元组数组,例如:

I want to convert it to an array of tuples like:

[(datetime.date(2012,2,17),24.75,25.03),
(datetime.date(2012,2,16),25.00,25.07),
...etc. ]

对我如何有效地做到这一点有什么建议吗?

Any suggestion on how I can efficiently do this?

推荐答案

list(data_set.itertuples(index=False))

从 17.1 开始,以上将返回一个 列表命名元组.

As of 17.1, the above will return a list of namedtuples.

如果你想要一个普通元组的列表,将 name=None 作为参数传递:

If you want a list of ordinary tuples, pass name=None as an argument:

list(data_set.itertuples(index=False, name=None))

这篇关于 pandas 将数据帧转换为元组数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆