Python 元组到数据帧转换的列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28200157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:53:48  来源:igfitidea点击:

List of Tuples to DataFrame Conversion

pythonlistpandastuples

提问by molivizzy

I have a list of tuples similar to the below:

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

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

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

我想将其转换为一个数据帧index=date1columns=ticker1values = values。做这个的最好方式是什么?

EDIT:

编辑:

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

我的最终目标是创建一个日期时间索引等于 date1 的 DataFrame,其值位于标记为“ticker”的列中:

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

Right now the tuple is generated with the following:

现在元组是用以下内容生成的:

tuples=list(zip(*prc_path))

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

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

回答by elyase

I think this is what you want:

我认为这就是你想要的:

>>> 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