元组列表到DataFrame的转换 [英] List of Tuples to DataFrame Conversion

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

问题描述

我有一个类似于以下内容的元组列表:

I have a list of tuples similar to the below:

[(date1, ticker1, value1),(date1, ticker1, value2),(date1, ticker1, value3)]

我想将其转换为具有index=date1columns=ticker1values = values的DataFrame.最好的方法是什么?

I want to convert this to a DataFrame with index=date1, columns=ticker1, and values = values. What is the best way to do this?

我的最终目标是创建一个日期时间索引等于date1的DataFrame,并在标记为"ticker"的列中添加值:

My end goal is to create a DataFrame with a datetimeindex equal to date1 with values in a column labeled 'ticker':

df = pd.DataFrame(tuples, index=date1)

现在,元组的生成如下:

Right now the tuple is generated with the following:

tuples=list(zip(*prc_path))

其中prc_path是形状为(1000,1)的numpy.ndarray

where prc_path is a numpy.ndarray with shape (1000,1)

推荐答案

我认为这是您想要的:

>>> data = [('2013-01-16', 'AAPL', 1),
            ('2013-01-16', 'GOOG', 1.5),
            ('2013-01-17', 'GOOG', 2),
            ('2013-01-17', 'MSFT', 4),
            ('2013-01-18', 'GOOG', 3),
            ('2013-01-18', 'MSFT', 3)]

>>> df = pd.DataFrame(data, columns=['date', 'ticker', 'value'])
>>> df
         date ticker  value
0  2013-01-16   AAPL    1.0
1  2013-01-16   GOOG    1.5
2  2013-01-17   GOOG    2.0
3  2013-01-17   MSFT    4.0
4  2013-01-18   GOOG    3.0
5  2013-01-18   MSFT    3.0

>>> df.pivot('date', 'ticker', 'value')
ticker      AAPL  GOOG  MSFT
date                        
2013-01-16     1   1.5   NaN
2013-01-17   NaN   2.0     4
2013-01-18   NaN   3.0     3

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

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