python - 如何在 Python 中访问多级 Pandas Dataframe - 在数据框中存储 Bloomberg 数据

标签 python pandas dataframe indexing

我已经安装了 Bloomberg API 和 pdblp 库。我能够获取历史数据并将其存储在 Dataframe 中。但我不确定如何从多级数据帧访问数据。

 import pdblp
 import pandas as pd

 con = pdblp.BCon(debug=True, port=8194)
 con.start()

 start = datetime.datetime.strptime("19800101", '%Y%m%d').strftime("%Y%m%d")
 end = datetime.date.today().strftime("%Y%m%d")


  df = pd.DataFrame(con.bdh('SPY US Equity',['PX_LAST', 'VOLUME'],start, end))
  print(df)

我无法访问 Dataframe 中的日期列。谁能帮帮我吗。 如果我尝试 -- df.columns 我得到以下输出:

   MultiIndex(levels=[['SPY US Equity'], ['PX_LAST', 'VOLUME']],
       labels=[[0, 0], [0, 1]],
       names=['ticker', 'field'])

以下是来自 Dataframe 的数据

 ticker     SPY US Equity             
field            PX_LAST       VOLUME
date                                 
1993-01-29       43.9375    1003200.0
1993-02-01       44.2500     480500.0
1993-02-02       44.3438     201300.0
1993-02-03       44.8125     529400.0
1993-02-04       45.0000     531500.0
1993-02-05       44.9688     492100.0
1993-02-08       44.9688     596100.0
1993-02-09       44.6563     122100.0
1993-02-10       44.7188     379600.0
1993-02-11       44.9375      19500.0
1993-02-12       44.5938      42500.0
1993-02-16       43.4688     374800.0
1993-02-17       43.4375     210900.0
1993-02-18       43.4063     378100.0
1993-02-19       43.5625      34900.0
1993-02-22       43.7188     513600.0
1993-02-23       43.6875     373700.0
1993-02-24       44.2500      26300.0
1993-02-25       44.3438      44500.0
1993-02-26       44.4063      66200.0
1993-03-01       44.2813      66500.0
1993-03-02       44.9375     182400.0

df.index 给出以下结果:

       DatetimeIndex(['1993-01-29', '1993-02-01', '1993-02-02', '1993-02-03',
           '1993-02-04', '1993-02-05', '1993-02-08', '1993-02-09',
           '1993-02-10', '1993-02-11',
           ...
           '2017-07-13', '2017-07-14', '2017-07-17', '2017-07-18',
           '2017-07-19', '2017-07-20', '2017-07-21', '2017-07-24',
           '2017-07-25', '2017-07-26'],
          dtype='datetime64[ns]', name='date', length=6168, freq=None)

df.loc['1993-02-22'] 给出以下结果:

  ticker         field  
  SPY US Equity  PX_LAST        43.7188
                 VOLUME     513600.0000

最佳答案

“日期”位于您的索引中。使用 reset_index 将其拉出。

df = df.reset_index()

现在,您可以使用以下命令查看“日期”列:

df['date']

关于python - 如何在 Python 中访问多级 Pandas Dataframe - 在数据框中存储 Bloomberg 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45331981/

相关文章:

python - 找不到匹配的 GLX 视觉

python - 在范围内合并 Pandas 数据框的最快方法

r - 在 R 中使用向量、现有变量和 mapply 创建多个新变量

python - Pandas:用空白替换重复值 groupby 像

python - 如何使用索引将 Pandas 数据框写入 sqlite

python - 如何在pandas中建立表的比较和更新功能?

python - 在 pandas DataFrame 中用 NaN 替换字符串(来自列表)

python - 如何用 pandas DataFrame 中之前和后续值的平均值替换 NaN?

python - 将 heroku django 应用程序与 ec2 postgres 数据库连接

python - Pygame关卡/菜单创建