pandas 数据框-将具有多个元素的时间序列转换为以元素为列的展平数据框 [英] Pandas dataframe - convert time series with multiple elements, to a flattened dataframe with elements as columns

查看:73
本文介绍了 pandas 数据框-将具有多个元素的时间序列转换为以元素为列的展平数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个存储在数据框中的时间序列数据集,其中包含多个元素,例如具有价格,市盈率和市盈率的股票-因此,每个报价器/日期有3行。我想知道是否有一种方法可以将其转换,因此每个行情自动收录器/日期有一行,价格,p / e和p / b作为列。

I have a time series dataset stored in a dataframe, with multiple elements, for example stocks with their price, p/e ratio, and p/b ratio - so I have 3 rows per ticker/date. I'm wondering if there is a way to convert this, so I have one row for each ticker/date, and the price,p/e, and p/b as columns.

示例数据框:

import pandas as pd

dfts = pd.DataFrame({
    'date': ['2020-01-01','2020-01-01','2020-01-01',
             '2020-01-01','2020-01-01','2020-01-01',
             '2020-01-02','2020-01-02','2020-01-02',
             '2020-01-02','2020-01-02','2020-01-02'],
    'ticker': ['AAPL','AAPL','AAPL',
               'GOOGL','GOOGL','GOOGL',
               'AAPL', 'AAPL', 'AAPL',
               'GOOGL', 'GOOGL', 'GOOGL'],
    'type': ['price','p/e','p/b',
             'price','p/e','p/b',
             'price','p/e','p/b',
             'price','p/e','p/b'],
    'value': [300,20,2,
              1000,25,3,
              310,21,2.1,
              1110,26,2.9]
})

print(dfts)

我希望将其转换并得到如下结果:

I'm looking to convert this and get a result such as:

Date        Ticker     Price     P/E     P/B
2020-01-01  AAPL       300       20      2
2020-01-02  AAPL       310       21      2.1
2020-01-01  GOOGL      1000      25      3
2020-01-02  GOOGL      1110      26      2.6

谢谢

推荐答案

检查下面的行是否有帮助

Check below lines if help you

将熊猫作为pd导入

dfts = pd.DataFrame({
    'date': ['2020-01-01','2020-01-01','2020-01-01',
             '2020-01-01','2020-01-01','2020-01-01',
             '2020-01-02','2020-01-02','2020-01-02',
             '2020-01-02','2020-01-02','2020-01-02'],
    'ticker': ['AAPL','AAPL','AAPL',
               'GOOGL','GOOGL','GOOGL',
               'AAPL', 'AAPL', 'AAPL',
               'GOOGL', 'GOOGL', 'GOOGL'],
    'type': ['price','p/e','p/b',
             'price','p/e','p/b',
             'price','p/e','p/b',
             'price','p/e','p/b'],
    'value': [300,20,2,
              1000,25,3,
              310,21,2.1,
              1110,26,2.9]
})
df = dfts.set_index(['date','ticker','type'])['value'].unstack().reset_index()
print(df)

输出框架是这样的-

这篇关于 pandas 数据框-将具有多个元素的时间序列转换为以元素为列的展平数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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