【问题标题】:Pandas groupby specific dataPandas groupby 特定数据
【发布时间】:2021-01-11 22:53:38
【问题描述】:

我有一个这样的数据框:
部门、名称、日期、价格

我想汇总我的数据,以便计算 3 年的波动率:

result = (df
          .groupby(['sector', 'name'])
               volat_3Y=('price', lambda x: 100*np.sqrt(252*np.log(x[-3*252:-1] / x[-3*252:-1].shift(1)).var()))            )

我还想计算 2020 年、2019 年...的性能,但是当我尝试时:

result = (df
          .groupby(['sector', 'name'])
               volat_3Y=('price', lambda x: 100*np.sqrt(252*np.log(x[-3*252:-1] / x[-3*252:-1].shift(1)).var()))
               perf_2020=('price', lambda x.loc['2020-09-18']) # Just to have access to a specific date 
               )

我有一条错误消息。有什么建议吗?

这是错误信息:


KeyError Traceback(最近一次调用最后一次) pandas._libs.index.DatetimeEngine.get_loc() 中的 pandas/_libs/index.pyx

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

密钥错误:1600387200000000000

在处理上述异常的过程中,又发生了一个异常:

KeyError Traceback(最近一次调用最后一次) ~/opt/anaconda3/envs/Data/lib/python3.8/site-packages/pandas/core/indexes/base.py in get_loc(self、key、method、tolerance) 2888 尝试: -> 2889 返回 self._engine.get_loc(casted_key) 2890 除了 KeyError 错误:

pandas/_libs/index.pyx in pandas._libs.index.DatetimeEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.DatetimeEngine.get_loc()

KeyError: Timestamp('2020-09-18 00:00:00')

【问题讨论】:

  • 我有一条错误消息,你为什么不把错误贴在这里?
  • 当我在一个组内做同样的事情时,我会添加:group.get_group(('sect1', 'nom1')).agg(perf_2020=('VL', lambda x: 100 *x.loc['2020-09-18'])) 我有一个数字:price perf_2020 10458.0

标签: python pandas dataframe


【解决方案1】:

这个公式对我有用:

result = (
    data
    .set_index('Date')
    .groupby(['Sector', 'Symbol'])
    .agg(
        volat_3Y = (
            'Price',
            lambda x: 100*np.sqrt(252*np.log(x[-3*252:-1] / x[-3*252:-1].shift(1)).var())),
        perf_2020_09_18 = (
            'Price',
            lambda x: x.loc['2020-09-18'])
    )
)

结果:

Sector Symbol volatility_3yr price_2020_09_18
Communication Services FB 38.1945 252.53
Communication Services GOOG 30.7639 1459.99
Communication Services NFLX 42.3228 469.96
Consumer Cyclical AMZN 32.613 2954.91
Technology AAPL 35.5864 106.5

完整示例代码:

import numpy as np
import pandas as pd
import pandas_datareader as pdr
import yfinance

symbols = ['FB', 'AMZN', 'AAPL', 'NFLX', 'GOOG']
sectors = [yfinance.Ticker(symbol).info['sector'] for symbol in symbols]
symbols_sectors = dict(zip(symbols, sectors))

raw_data = pdr.get_data_stooq(symbols).Close
data = (
    # get raw data
    raw_data
    # clean up names
    .set_axis(list(raw_data.columns), 1)
    .sort_index()
    .reset_index()
    # transform to long form
    .melt('Date', var_name='Symbol', value_name='Price')
    # attach sector names
    .assign(Sector = lambda x: x.Symbol.map(symbols_sectors))
)

result = (
    data
    .set_index('Date')
    .groupby(['Sector', 'Symbol'])
    .agg(
        volatility_3yr = (
            'Price',
            lambda x: 100*np.sqrt(252*np.log(x[-3*252:-1] / x[-3*252:-1].shift(1)).var())),
        price_2020_09_18 = (
            'Price',
            lambda x: x.loc['2020-09-18'])
    )
)

print(result.reset_index().to_markdown(index=False))

【讨论】:

    猜你喜欢
    • 2020-02-06
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 2021-04-25
    • 2020-06-19
    • 1970-01-01
    • 2018-10-02
    • 2021-01-17
    相关资源
    最近更新 更多